author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
259,891
13.07.2022 10:17:57
25,200
d67ff8ac9b5156f81f9efa7f6bd8d16c163b1661
use PACKET_MMAP for rx when supported This was fixed in 5.6-rc7, so we enable PACKET_MMAP for all kernels >= 5.6. Downloads in iperf go from ~90MB/s to ~102MB/s.
[ { "change_type": "MODIFY", "old_path": "runsc/boot/BUILD", "new_path": "runsc/boot/BUILD", "diff": "@@ -119,6 +119,7 @@ go_library(\n\"//runsc/specutils/seccomp\",\n\"@com_github_opencontainers_runtime_spec//specs-go:go_default_library\",\n\"@org_golang_google_protobuf//proto:go_default_library\",\n+ \"@org_golang_x_mod//semver:go_default_library\",\n\"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/network.go", "new_path": "runsc/boot/network.go", "diff": "@@ -17,9 +17,11 @@ package boot\nimport (\n\"fmt\"\n\"net\"\n+ \"regexp\"\n\"runtime\"\n\"strings\"\n+ \"golang.org/x/mod/semver\"\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n@@ -194,6 +196,22 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\n}\n}\n+ // Choose a dispatch mode.\n+ // Get the Linux kernel version. Uname will return something like\n+ // \"5.17.7-1distro-amd64\", from which we'd want \"5.17.7\".\n+ var uname unix.Utsname\n+ if err := unix.Uname(&uname); err != nil {\n+ return err\n+ }\n+ re := regexp.MustCompile(`[0-9]+\\.[0-9]+(\\.[0-9]+)?`)\n+ version := \"v\" + string(re.Find(uname.Release[:]))\n+ dispatchMode := fdbased.RecvMMsg\n+ if semver.IsValid(version) && semver.Compare(version, \"v5.6\") >= 0 {\n+ dispatchMode = fdbased.PacketMMap\n+ } else {\n+ log.Infof(\"Host kernel version < 5.6, falling back to RecvMMsg dispatch\")\n+ }\n+\nfdOffset := 0\nfor _, link := range args.FDBasedLinks {\nnicID++\n@@ -219,7 +237,7 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\nMTU: uint32(link.MTU),\nEthernetHeader: mac != \"\",\nAddress: mac,\n- PacketDispatchMode: fdbased.RecvMMsg,\n+ PacketDispatchMode: dispatchMode,\nGSOMaxSize: link.GSOMaxSize,\nGvisorGSOEnabled: link.GvisorGSOEnabled,\nTXChecksumOffload: link.TXChecksumOffload,\n" } ]
Go
Apache License 2.0
google/gvisor
use PACKET_MMAP for rx when supported This was fixed in 5.6-rc7, so we enable PACKET_MMAP for all kernels >= 5.6. Downloads in iperf go from ~90MB/s to ~102MB/s. PiperOrigin-RevId: 460746326
259,891
13.07.2022 15:12:53
25,200
63bb6e7e6900e0ca474787966b00ccfb7a775ae9
typo: mismatched variable and comment
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/ipv6_extension_headers.go", "new_path": "pkg/tcpip/header/ipv6_extension_headers.go", "diff": "@@ -248,7 +248,7 @@ const (\n// provides 1 byte padding, as outlined in RFC 8200 section 4.2.\nipv6Pad1ExtHdrOptionIdentifier IPv6ExtHdrOptionIdentifier = 0\n- // ipv6PadBExtHdrOptionIdentifier is the identifier for a padding option that\n+ // ipv6PadNExtHdrOptionIdentifier is the identifier for a padding option that\n// provides variable length byte padding, as outlined in RFC 8200 section 4.2.\nipv6PadNExtHdrOptionIdentifier IPv6ExtHdrOptionIdentifier = 1\n" } ]
Go
Apache License 2.0
google/gvisor
typo: mismatched variable and comment PiperOrigin-RevId: 460814306
259,891
13.07.2022 21:26:41
25,200
2ceb6bb1f89d82105ab30d4b8ae280a7273cf91c
Use hostos.KernelVersion everywhere, and have it return semver strings
[ { "change_type": "MODIFY", "old_path": "pkg/coretag/coretag_test.go", "new_path": "pkg/coretag/coretag_test.go", "diff": "@@ -22,14 +22,14 @@ import (\n)\nfunc TestEnable(t *testing.T) {\n- major, minor, err := hostos.KernelVersion()\n+ version, err := hostos.KernelVersion()\nif err != nil {\nt.Fatalf(\"Unable to parse kernel version: %v\", err)\n}\n// Skip running test when running on Linux kernel < 5.14 because core tagging\n// is not available.\n- if major < 5 && minor < 14 {\n- t.Skipf(\"Running on Linux kernel: %d.%d < 5.14. Core tagging not available. Skipping test.\", major, minor)\n+ if version.LessThan(5, 14) {\n+ t.Skipf(\"Running on Linux kernel: %s < 5.14. Core tagging not available. Skipping test.\", version)\nreturn\n}\nif err := Enable(); err != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/cpuid/cpuid_parse_amd64_test.go", "new_path": "pkg/cpuid/cpuid_parse_amd64_test.go", "diff": "package cpuid\n-func archSkipFeature(feature Feature, major, minor int) bool {\n+import \"gvisor.dev/gvisor/pkg/hostos\"\n+\n+func archSkipFeature(feature Feature, version hostos.Version) bool {\nswitch {\n// Block 0.\n- case feature == X86FeatureSDBG && (major < 4 || major == 4 && minor < 3):\n+ case feature == X86FeatureSDBG && version.AtLeast(4, 3):\n// SDBG only exposed in\n// b1c599b8ff80ea79b9f8277a3f9f36a7b0cfedce (4.3).\nreturn true\n// Block 2.\n- case feature == X86FeatureRDT && (major < 4 || major == 4 && minor < 10):\n+ case feature == X86FeatureRDT && version.AtLeast(4, 10):\n// RDT only exposed in\n// 4ab1586488cb56ed8728e54c4157cc38646874d9 (4.10).\nreturn true\n// Block 3.\n- case feature == X86FeatureAVX512VBMI && (major < 4 || major == 4 && minor < 10):\n+ case feature == X86FeatureAVX512VBMI && version.AtLeast(4, 10):\n// AVX512VBMI only exposed in\n// a8d9df5a509a232a959e4ef2e281f7ecd77810d6 (4.10).\nreturn true\n- case feature == X86FeatureUMIP && (major < 4 || major == 4 && minor < 15):\n+ case feature == X86FeatureUMIP && version.AtLeast(4, 15):\n// UMIP only exposed in\n// 3522c2a6a4f341058b8291326a945e2a2d2aaf55 (4.15).\nreturn true\n- case feature == X86FeaturePKU && (major < 4 || major == 4 && minor < 9):\n+ case feature == X86FeaturePKU && version.AtLeast(4, 9):\n// PKU only exposed in\n// dfb4a70f20c5b3880da56ee4c9484bdb4e8f1e65 (4.9).\nreturn true\n// Block 4.\n- case feature == X86FeatureXSAVES && (major < 4 || major == 4 && minor < 8):\n+ case feature == X86FeatureXSAVES && version.AtLeast(4, 8):\n// XSAVES only exposed in\n// b8be15d588060a03569ac85dc4a0247460988f5b (4.8).\nreturn true\n// Block 5.\n- case feature == X86FeaturePERFCTR_LLC && (major < 4 || major == 4 && minor < 14):\n+ case feature == X86FeaturePERFCTR_LLC && version.AtLeast(4, 14):\n// PERFCTR_LLC renamed in\n// 910448bbed066ab1082b510eef1ae61bb792d854 (4.14).\nreturn true\n" }, { "change_type": "MODIFY", "old_path": "pkg/cpuid/cpuid_parse_arm64_test.go", "new_path": "pkg/cpuid/cpuid_parse_arm64_test.go", "diff": "package cpuid\n-func archSkipFeature(feature Feature, major, minor int) bool {\n+func archSkipFeature(feature Feature, version hostos.Version) bool {\nreturn false\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/cpuid/cpuid_parse_test.go", "new_path": "pkg/cpuid/cpuid_parse_test.go", "diff": "@@ -31,7 +31,7 @@ import (\n// analog in the actual CPUID feature set.\nfunc TestHostFeatureFlags(t *testing.T) {\n// Extract the kernel version.\n- major, minor, err := hostos.KernelVersion()\n+ version, err := hostos.KernelVersion()\nif err != nil {\nt.Fatalf(\"Unable to parse kernel version: %v\", err)\n}\n@@ -54,7 +54,7 @@ func TestHostFeatureFlags(t *testing.T) {\nfor feature, info := range allFeatures {\n// Special cases not consistently visible. We don't mind if\n// they are exposed in earlier versions.\n- if archSkipFeature(feature, major, minor) {\n+ if archSkipFeature(feature, version) {\ncontinue\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/hostos/BUILD", "new_path": "pkg/hostos/BUILD", "diff": "@@ -6,5 +6,8 @@ go_library(\nname = \"hostos\",\nsrcs = [\"hostos.go\"],\nvisibility = [\"//:sandbox\"],\n- deps = [\"@org_golang_x_sys//unix:go_default_library\"],\n+ deps = [\n+ \"@org_golang_x_mod//semver:go_default_library\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/hostos/hostos.go", "new_path": "pkg/hostos/hostos.go", "diff": "@@ -17,41 +17,71 @@ package hostos\nimport (\n\"fmt\"\n- \"strconv\"\n+ \"regexp\"\n\"strings\"\n+ \"sync\"\n+ \"golang.org/x/mod/semver\"\n\"golang.org/x/sys/unix\"\n)\n-// KernelVersion returns the major and minor release version of the kernel using uname().\n-func KernelVersion() (int, int, error) {\n- var u unix.Utsname\n- if err := unix.Uname(&u); err != nil {\n- return 0, 0, err\n+// Version represents a semantic version of the form \"%d.%d[.%d]\".\n+type Version struct {\n+ version string\n}\n- var sb strings.Builder\n- for _, b := range u.Release {\n- if b == 0 {\n- break\n+// AtLeast returns whether vr is at least version major.minor.\n+func (vr Version) AtLeast(major, minor int) bool {\n+ return semver.Compare(vr.version, fmt.Sprintf(\"v%d.%d\", major, minor)) >= 0\n}\n- sb.WriteByte(byte(b))\n+\n+// LessThan returns whether vr is less than version major.minor.\n+func (vr Version) LessThan(major, minor int) bool {\n+ return !vr.AtLeast(major, minor)\n}\n- s := strings.Split(sb.String(), \".\")\n- if len(s) < 2 {\n- return 0, 0, fmt.Errorf(\"kernel release missing major and minor component: %s\", sb.String())\n+// String implements fmt.Stringer.\n+func (vr Version) String() string {\n+ if vr.version == \"\" {\n+ return \"unknown\"\n+ }\n+ // Omit the \"v\" prefix required by semver.\n+ return vr.version[1:]\n}\n- major, err := strconv.Atoi(s[0])\n- if err != nil {\n- return 0, 0, fmt.Errorf(\"error parsing major version %q in %q: %w\", s[0], sb.String(), err)\n+// These values are effectively local to KernelVersion, but kept here so as to\n+// work with sync.Once.\n+var (\n+ semVersion Version\n+ unameErr error\n+ once sync.Once\n+)\n+\n+// KernelVersion returns the version of the kernel using uname().\n+func KernelVersion() (Version, error) {\n+ once.Do(func() {\n+ var utsname unix.Utsname\n+ if err := unix.Uname(&utsname); err != nil {\n+ unameErr = err\n+ return\n+ }\n+\n+ var sb strings.Builder\n+ for _, b := range utsname.Release {\n+ if b == 0 {\n+ break\n+ }\n+ sb.WriteByte(byte(b))\n}\n- minor, err := strconv.Atoi(s[1])\n- if err != nil {\n- return 0, 0, fmt.Errorf(\"error parsing minor version %q in %q: %w\", s[1], sb.String(), err)\n+ versionRegexp := regexp.MustCompile(`[0-9]+\\.[0-9]+(\\.[0-9]+)?`)\n+ version := \"v\" + string(versionRegexp.Find([]byte(sb.String())))\n+ if !semver.IsValid(version) {\n+ unameErr = fmt.Errorf(\"invalid version found in release %q\", sb.String())\n+ return\n}\n+ semVersion.version = version\n+ })\n- return major, minor, nil\n+ return semVersion, unameErr\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/BUILD", "new_path": "runsc/boot/BUILD", "diff": "@@ -40,6 +40,7 @@ go_library(\n\"//pkg/fd\",\n\"//pkg/flipcall\",\n\"//pkg/fspath\",\n+ \"//pkg/hostos\",\n\"//pkg/log\",\n\"//pkg/memutil\",\n\"//pkg/rand\",\n@@ -119,7 +120,6 @@ go_library(\n\"//runsc/specutils/seccomp\",\n\"@com_github_opencontainers_runtime_spec//specs-go:go_default_library\",\n\"@org_golang_google_protobuf//proto:go_default_library\",\n- \"@org_golang_x_mod//semver:go_default_library\",\n\"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/network.go", "new_path": "runsc/boot/network.go", "diff": "@@ -17,12 +17,11 @@ package boot\nimport (\n\"fmt\"\n\"net\"\n- \"regexp\"\n\"runtime\"\n\"strings\"\n- \"golang.org/x/mod/semver\"\n\"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/hostos\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/ethernet\"\n@@ -197,16 +196,12 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\n}\n// Choose a dispatch mode.\n- // Get the Linux kernel version. Uname will return something like\n- // \"5.17.7-1distro-amd64\", from which we'd want \"5.17.7\".\n- var uname unix.Utsname\n- if err := unix.Uname(&uname); err != nil {\n+ dispatchMode := fdbased.RecvMMsg\n+ version, err := hostos.KernelVersion()\n+ if err != nil {\nreturn err\n}\n- re := regexp.MustCompile(`[0-9]+\\.[0-9]+(\\.[0-9]+)?`)\n- version := \"v\" + string(re.Find(uname.Release[:]))\n- dispatchMode := fdbased.RecvMMsg\n- if semver.IsValid(version) && semver.Compare(version, \"v5.6\") >= 0 {\n+ if version.AtLeast(5, 6) {\ndispatchMode = fdbased.PacketMMap\n} else {\nlog.Infof(\"Host kernel version < 5.6, falling back to RecvMMsg dispatch\")\n" } ]
Go
Apache License 2.0
google/gvisor
Use hostos.KernelVersion everywhere, and have it return semver strings PiperOrigin-RevId: 460872657
260,000
11.07.2022 13:44:58
25,200
48daa2225f4c1d1269b58d6dc4a54a4bb40b9241
context: initialize and use bgContext once bgContext is set during package initialization. However, the global logger's SetTarget() method doesn't apply to instances of context.Background() loaded after the first one. See
[ { "change_type": "MODIFY", "old_path": "pkg/context/context.go", "new_path": "pkg/context/context.go", "diff": "@@ -24,6 +24,7 @@ package context\nimport (\n\"context\"\n+ \"sync\"\n\"time\"\n\"gvisor.dev/gvisor/pkg/log\"\n@@ -162,10 +163,8 @@ type logContext struct {\n}\n// bgContext is the context returned by context.Background.\n-var bgContext Context = &logContext{\n- Context: context.Background(),\n- Logger: log.Log(),\n-}\n+var bgContext Context\n+var bgOnce sync.Once\n// Background returns an empty context using the default logger.\n// Generally, one should use the Task as their context when available, or avoid\n@@ -173,7 +172,15 @@ var bgContext Context = &logContext{\n//\n// Using a Background context for tests is fine, as long as no values are\n// needed from the context in the tested code paths.\n+//\n+// The global log.SetTarget() must be called before context.Background()\nfunc Background() Context {\n+ bgOnce.Do(func() {\n+ bgContext = &logContext{\n+ Context: context.Background(),\n+ Logger: log.Log(),\n+ }\n+ })\nreturn bgContext\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/log/log.go", "new_path": "pkg/log/log.go", "diff": "@@ -260,6 +260,8 @@ func Log() *BasicLogger {\n//\n// This is not thread safe and shouldn't be called concurrently with any\n// logging calls.\n+//\n+// SetTarget should be called before any instances of log.Log() to avoid race conditions\nfunc SetTarget(target Emitter) {\nlogMu.Lock()\ndefer logMu.Unlock()\n" } ]
Go
Apache License 2.0
google/gvisor
context: initialize and use bgContext once bgContext is set during package initialization. However, the global logger's SetTarget() method doesn't apply to instances of context.Background() loaded after the first one. See https://github.com/google/gvisor/issues/7795
259,868
18.07.2022 15:12:38
25,200
cb935d751201154d46f9c4e27e902648d4ce0cdf
gVisor benchmarks: Add "Ruby CI/CD experience" benchmarks. This adds two benchmarks: A no-op Ruby unit test, based off the Stripe benchmark: A more serious unit test suite from Fastlane, a large Ruby project:
[ { "change_type": "MODIFY", "old_path": ".buildkite/pipeline.yaml", "new_path": ".buildkite/pipeline.yaml", "diff": "@@ -402,6 +402,9 @@ steps:\n- <<: *benchmarks\nlabel: \":cd: FIO benchmarks (randread/randwrite)\"\ncommand: make -i benchmark-platforms BENCHMARKS_SUITE=fio BENCHMARKS_TARGETS=test/benchmarks/fs:fio_test BENCHMARKS_FILTER=Fio/operation\\.rand BENCHMARKS_OPTIONS=--test.benchtime=15s\n+ - <<: *benchmarks\n+ label: \":cd: Ruby CI/CD benchmarks\"\n+ command: make -i benchmark-platforms BENCHMARKS_SUITE=fio BENCHMARKS_TARGETS=test/benchmarks/fs:rubydev_test BENCHMARKS_OPTIONS=-test.benchtime=1ns\n- <<: *benchmarks\nlabel: \":globe_with_meridians: HTTPD benchmarks\"\ncommand: make -i benchmark-platforms BENCHMARKS_FILTER=\"Continuous\" BENCHMARKS_SUITE=httpd BENCHMARKS_TARGETS=test/benchmarks/network:httpd_test\n" }, { "change_type": "ADD", "old_path": null, "new_path": "images/benchmarks/rubydev/Dockerfile", "diff": "+FROM ruby:3.0-alpine\n+\n+# Some of these dependencies are called as subprocesses by the fastlane tests.\n+RUN apk add --no-cache ruby ruby-dev ruby-bundler ruby-json build-base bash \\\n+ wget git unzip\n+RUN wget -q \\\n+ 'https://github.com/fastlane/fastlane/archive/refs/tags/2.207.0.tar.gz' \\\n+ -O /tmp/fastlane.tar.gz \\\n+ && mkdir /fastlane \\\n+ && cd /fastlane \\\n+ && tar xfz /tmp/fastlane.tar.gz --strip-components=1 \\\n+ && rm /tmp/fastlane.tar.gz \\\n+ && for i in 1 2 3; do if bundle install; then break; fi; done\n+COPY . /files/\n" }, { "change_type": "ADD", "old_path": null, "new_path": "images/benchmarks/rubydev/run_fastlane_tests.sh", "diff": "+#!/bin/bash\n+# Copyright 2022 The gVisor Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+set -euo pipefail\n+\n+# Run only a subset of tests, otherwise this is simply too long of a benchmark.\n+# This list was compiled using:\n+# $ find -name '*_spec.rb' | shuf | head -100 | cut -d/ -f2- | sort\n+specs=(\n+ cert/spec/commands_generator_spec.rb\n+ credentials_manager/spec/account_manager_spec.rb\n+ fastlane/spec/action_metadata_spec.rb\n+ fastlane/spec/actions_helper_spec.rb\n+ fastlane/spec/actions_specs/appetize_view_url_generator_spec.rb\n+ fastlane/spec/actions_specs/apteligent_spec.rb\n+ fastlane/spec/actions_specs/backup_file_spec.rb\n+ fastlane/spec/actions_specs/clean_cocoapods_cache_spec.rb\n+ fastlane/spec/actions_specs/delete_keychain_spec.rb\n+ fastlane/spec/actions_specs/deploygate_spec.rb\n+ fastlane/spec/actions_specs/ensure_git_status_clean_spec.rb\n+ fastlane/spec/actions_specs/ensure_xcode_version_spec.rb\n+ fastlane/spec/actions_specs/get_github_release_spec.rb\n+ fastlane/spec/actions_specs/git_branch_spec.rb\n+ fastlane/spec/actions_specs/git_pull_spec.rb\n+ fastlane/spec/actions_specs/hg_add_tag_spec.rb\n+ fastlane/spec/actions_specs/hg_commit_version_bump_spec.rb\n+ fastlane/spec/actions_specs/hockey_spec.rb\n+ fastlane/spec/actions_specs/import_certificate_spec.rb\n+ fastlane/spec/actions_specs/import_spec.rb\n+ fastlane/spec/actions_specs/jazzy_spec.rb\n+ fastlane/spec/actions_specs/push_git_tags_spec.rb\n+ fastlane/spec/actions_specs/puts_spec.rb\n+ fastlane/spec/actions_specs/reset_git_repo_spec.rb\n+ fastlane/spec/actions_specs/rsync_spec.rb\n+ fastlane/spec/actions_specs/say_spec.rb\n+ fastlane/spec/actions_specs/set_changelog_spec.rb\n+ fastlane/spec/actions_specs/set_info_plist_value_spec.rb\n+ fastlane/spec/actions_specs/set_pod_key_spec.rb\n+ fastlane/spec/actions_specs/setup_ci_spec.rb\n+ fastlane/spec/actions_specs/setup_circle_ci_spec.rb\n+ fastlane/spec/actions_specs/spm_spec.rb\n+ fastlane/spec/actions_specs/swiftlint_spec.rb\n+ fastlane/spec/actions_specs/testfairy_spec.rb\n+ fastlane/spec/actions_specs/update_app_identifier_spec.rb\n+ fastlane/spec/actions_specs/update_keychain_access_groups_spec.rb\n+ fastlane/spec/actions_specs/update_project_provisioning_spec.rb\n+ fastlane/spec/actions_specs/version_bump_podspec_spec.rb\n+ fastlane/spec/actions_specs/xcode_server_get_assets_spec.rb\n+ fastlane/spec/actions_specs/xcodebuild_spec.rb\n+ fastlane/spec/actions_specs/xctool_action_spec.rb\n+ fastlane/spec/actions_specs/zip_spec.rb\n+ fastlane/spec/command_line_handler_spec.rb\n+ fastlane/spec/env_spec.rb\n+ fastlane/spec/gradle_helper_spec.rb\n+ fastlane/spec/helper/adb_helper_spec.rb\n+ fastlane/spec/helper/s3_client_helper_spec.rb\n+ fastlane/spec/helper/xcodeproj_helper_spec.rb\n+ fastlane/spec/lane_list_spec.rb\n+ fastlane/spec/runner_spec.rb\n+ fastlane_core/spec/app_identifier_guesser_spec.rb\n+ fastlane_core/spec/configuration_file_spec.rb\n+ fastlane_core/spec/configuration_spec.rb\n+ fastlane_core/spec/core_ext/cfpropertylist_ext_spec.rb\n+ fastlane_core/spec/core_ext/shellwords_ext_spec.rb\n+ fastlane_core/spec/fastlane_user_dir_spec.rb\n+ fastlane_core/spec/ios_app_identifier_guesser_spec.rb\n+ fastlane_core/spec/languages_spec.rb\n+ gym/spec/code_signing_mapping_spec.rb\n+ gym/spec/gymfile_spec.rb\n+ gym/spec/options_spec.rb\n+ gym/spec/xcodebuild_fixes/generic_archive_fix_spec.rb\n+ match/spec/encryption/openssl_spec.rb\n+ match/spec/storage/gitlab/client_spec.rb\n+ precheck/spec/rules/curse_words_rule_spec.rb\n+ precheck/spec/rules/rule_spec.rb\n+ precheck/spec/rules/unreachable_urls_rule_spec.rb\n+ scan/spec/commands_generator_spec.rb\n+ scan/spec/error_handler_spec.rb\n+ scan/spec/test_result_parser_spec.rb\n+ screengrab/spec/commands_generator_spec.rb\n+ sigh/spec/manager_spec.rb\n+ sigh/spec/runner_spec.rb\n+ snapshot/spec/test_command_generator_xcode_8_spec.rb\n+ spaceship/spec/connect_api/client_spec.rb\n+ spaceship/spec/connect_api/models/app_spec.rb\n+ spaceship/spec/connect_api/models/app_store_version_spec.rb\n+ spaceship/spec/connect_api/models/beta_feedback_spec.rb\n+ spaceship/spec/connect_api/models/build_beta_detail_spec.rb\n+ spaceship/spec/connect_api/models/build_delivery_spec.rb\n+ spaceship/spec/connect_api/models/bundle_id_spec.rb\n+ spaceship/spec/connect_api/testflight/testflight_client_spec.rb\n+ spaceship/spec/connect_api/token_spec.rb\n+ spaceship/spec/du/du_client_spec.rb\n+ spaceship/spec/portal/app_group_spec.rb\n+ spaceship/spec/portal/app_spec.rb\n+ spaceship/spec/portal/enterprise_spec.rb\n+ spaceship/spec/portal/merchant_spec.rb\n+ spaceship/spec/portal/passbook_spec.rb\n+ spaceship/spec/spaceship_base_spec.rb\n+ spaceship/spec/spaceship_spec.rb\n+ spaceship/spec/test_flight/app_test_info_spec.rb\n+ spaceship/spec/tunes/app_analytics_spec.rb\n+ spaceship/spec/tunes/app_submission_spec.rb\n+ spaceship/spec/tunes/app_version_spec.rb\n+ spaceship/spec/tunes/application_spec.rb\n+ spaceship/spec/tunes/b2b_organization_spec.rb\n+ spaceship/spec/tunes/members_spec.rb\n+ spaceship/spec/two_step_or_factor_client_spec.rb\n+ supply/spec/commands_generator_spec.rb\n+)\n+pattern=\"{\"\n+for spec in \"${specs[@]}\"; do\n+ pattern=\"${pattern}${spec},\"\n+done\n+pattern=\"$(echo \"$pattern\" | sed -r 's/,$//')}\"\n+exec bundle exec rspec --pattern \"$pattern\"\n" }, { "change_type": "ADD", "old_path": null, "new_path": "images/benchmarks/rubydev/tc_no_op.rb", "diff": "+# A unit test that tests nothing.\n+# Based on the unit test that Stripe used to benchmark gVisor:\n+# https://stripe.com/blog/fast-secure-builds-choose-two\n+\n+require \"test/unit\"\n+\n+class TestNoOp < Test::Unit::TestCase\n+ def test_noop\n+ end\n+end\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/fs/BUILD", "new_path": "test/benchmarks/fs/BUILD", "diff": "@@ -9,6 +9,7 @@ benchmark_test(\ndeps = [\n\"//pkg/cleanup\",\n\"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/fs/fsbench\",\n\"//test/benchmarks/harness\",\n\"//test/benchmarks/tools\",\n\"@com_github_docker_docker//api/types/mount:go_default_library\",\n@@ -27,3 +28,14 @@ benchmark_test(\n\"@com_github_docker_docker//api/types/mount:go_default_library\",\n],\n)\n+\n+benchmark_test(\n+ name = \"rubydev_test\",\n+ srcs = [\"rubydev_test.go\"],\n+ visibility = [\"//:sandbox\"],\n+ deps = [\n+ \"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/fs/fsbench\",\n+ \"//test/benchmarks/harness\",\n+ ],\n+)\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/fs/bazel_test.go", "new_path": "test/benchmarks/fs/bazel_test.go", "diff": "// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n+\n+// Package bazel_test benchmarks builds using bazel.\npackage bazel_test\nimport (\n\"context\"\n- \"fmt\"\n\"os\"\n- \"strings\"\n\"testing\"\n- \"gvisor.dev/gvisor/pkg/cleanup\"\n- \"gvisor.dev/gvisor/pkg/test/dockerutil\"\n+ \"gvisor.dev/gvisor/test/benchmarks/fs/fsbench\"\n\"gvisor.dev/gvisor/test/benchmarks/harness\"\n- \"gvisor.dev/gvisor/test/benchmarks/tools\"\n)\n-// Dimensions here are clean/dirty cache (do or don't drop caches)\n-// and if the mount on which we are compiling is a tmpfs/bind mount.\n-type benchmark struct {\n- clearCache bool // clearCache drops caches before running.\n- fstype harness.FileSystemType // type of filesystem to use.\n-}\n-\n// Note: CleanCache versions of this test require running with root permissions.\nfunc BenchmarkBuildABSL(b *testing.B) {\nrunBuildBenchmark(b, \"benchmarks/absl\", \"/abseil-cpp\", \"absl/base/...\")\n@@ -50,113 +41,23 @@ func BenchmarkBuildGRPC(b *testing.B) {\nrunBuildBenchmark(b, \"benchmarks/build-grpc\", \"/grpc\", \":grpc\")\n}\n-func runBuildBenchmark(b *testing.B, image, workdir, target string) {\n+func runBuildBenchmark(b *testing.B, image, workDir, target string) {\nb.Helper()\n+ ctx := context.Background()\n// Get a machine from the Harness on which to run.\nmachine, err := harness.GetMachine()\nif err != nil {\nb.Fatalf(\"Failed to get machine: %v\", err)\n}\ndefer machine.CleanUp()\n-\n- benchmarks := make([]benchmark, 0, 6)\n- for _, filesys := range []harness.FileSystemType{harness.BindFS, harness.TmpFS, harness.RootFS} {\n- benchmarks = append(benchmarks, benchmark{\n- clearCache: true,\n- fstype: filesys,\n- })\n- benchmarks = append(benchmarks, benchmark{\n- clearCache: false,\n- fstype: filesys,\n- })\n- }\n-\n- for _, bm := range benchmarks {\n- pageCache := tools.Parameter{\n- Name: \"page_cache\",\n- Value: \"dirty\",\n- }\n- if bm.clearCache {\n- pageCache.Value = \"clean\"\n- }\n-\n- filesystem := tools.Parameter{\n- Name: \"filesystem\",\n- Value: string(bm.fstype),\n- }\n- name, err := tools.ParametersToName(pageCache, filesystem)\n- if err != nil {\n- b.Fatalf(\"Failed to parse parameters: %v\", err)\n- }\n-\n- b.Run(name, func(b *testing.B) {\n- // Grab a container.\n- ctx := context.Background()\n- container := machine.GetContainer(ctx, b)\n- cu := cleanup.Make(func() {\n- container.CleanUp(ctx)\n- })\n- defer cu.Clean()\n- mts, prefix, err := harness.MakeMount(machine, bm.fstype, &cu)\n- if err != nil {\n- b.Fatalf(\"Failed to make mount: %v\", err)\n- }\n-\n- runOpts := dockerutil.RunOpts{\n+ fsbench.RunWithDifferentFilesystems(ctx, b, machine, fsbench.FSBenchmark{\nImage: image,\n- Mounts: mts,\n- }\n-\n- // Start a container and sleep.\n- if err := container.Spawn(ctx, runOpts, \"sleep\", fmt.Sprintf(\"%d\", 1000000)); err != nil {\n- b.Fatalf(\"run failed with: %v\", err)\n- }\n-\n- cpCmd := fmt.Sprintf(\"mkdir -p %s && cp -r %s %s/.\", prefix, workdir, prefix)\n- if out, err := container.Exec(ctx, dockerutil.ExecOpts{},\n- \"/bin/sh\", \"-c\", cpCmd); err != nil {\n- b.Fatalf(\"failed to copy directory: %v (%s)\", err, out)\n- }\n-\n- b.ResetTimer()\n- b.StopTimer()\n-\n- // Drop Caches and bazel clean should happen inside the loop as we may use\n- // time options with b.N. (e.g. Run for an hour.)\n- for i := 0; i < b.N; i++ {\n- // Drop Caches for clear cache runs.\n- if bm.clearCache {\n- if err := harness.DropCaches(machine); err != nil {\n- b.Skipf(\"failed to drop caches: %v. You probably need root.\", err)\n- }\n- }\n-\n- b.StartTimer()\n- got, err := container.Exec(ctx, dockerutil.ExecOpts{\n- WorkDir: prefix + workdir,\n- }, \"bazel\", \"build\", \"-c\", \"opt\", target)\n- if err != nil {\n- b.Fatalf(\"build failed with: %v logs: %s\", err, got)\n- }\n- b.StopTimer()\n-\n- want := \"Build completed successfully\"\n- if !strings.Contains(got, want) {\n- b.Fatalf(\"string %s not in: %s\", want, got)\n- }\n-\n- // Clean bazel in the case we are doing another run.\n- if i < b.N-1 {\n- if _, err = container.Exec(ctx, dockerutil.ExecOpts{\n- WorkDir: prefix + workdir,\n- }, \"bazel\", \"clean\"); err != nil {\n- b.Fatalf(\"build failed with: %v\", err)\n- }\n- }\n- }\n+ WorkDir: workDir,\n+ RunCmd: []string{\"bazel\", \"build\", \"-c\", \"opt\", target},\n+ WantOutput: \"Build completed successfully\",\n+ CleanCmd: []string{\"blaze\", \"clean\"},\n})\n}\n-}\n// TestMain is the main method for package fs.\nfunc TestMain(m *testing.M) {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/benchmarks/fs/fsbench/BUILD", "diff": "+# Package fsbench provides utility functions for filesystem-related benchmarks.\n+\n+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+package(\n+ default_visibility = [\"//test/benchmarks/fs:__subpackages__\"],\n+ licenses = [\"notice\"],\n+)\n+\n+go_library(\n+ name = \"fsbench\",\n+ testonly = 1,\n+ srcs = [\"fsbench.go\"],\n+ deps = [\n+ \"//pkg/cleanup\",\n+ \"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/harness\",\n+ \"//test/benchmarks/tools\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/benchmarks/fs/fsbench/fsbench.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package fsbench provides utility functions for filesystem benchmarks.\n+package fsbench\n+\n+import (\n+ \"context\"\n+ \"fmt\"\n+ \"strings\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/cleanup\"\n+ \"gvisor.dev/gvisor/pkg/test/dockerutil\"\n+ \"gvisor.dev/gvisor/test/benchmarks/harness\"\n+ \"gvisor.dev/gvisor/test/benchmarks/tools\"\n+)\n+\n+// FSBenchmark represents a set of work to perform within a container that is instrumented with\n+// different filesystem configurations.\n+type FSBenchmark struct {\n+ // Image is the Docker image to load.\n+ Image string\n+ // WorkDir is where the action takes place.\n+ // The commands below are run from a directory that has the same file as what the container image\n+ // has at this directory.\n+ WorkDir string\n+ // RunCmd is the command to run to execute the benchmark.\n+ RunCmd []string\n+ // WantOutput, if set, is verified to be a substring of the output of RunCmd.\n+ WantOutput string\n+ // CleanCmd, if set, is run to clean up between benchmarks.\n+ CleanCmd []string\n+ // Variants is a list of benchmarka variants to run.\n+ // If unset, the typical set is used.\n+ Variants []Variant\n+}\n+\n+// Variant is a specific configuration for a benchmark.\n+// Dimensions here are clean/dirty cache (do or don't drop caches)\n+// and if the mount on which we are compiling is a tmpfs/bind mount.\n+type Variant struct {\n+ // clearCache drops caches before running.\n+ clearCache bool\n+ // fsType is the type of filesystem to use.\n+ fsType harness.FileSystemType\n+}\n+\n+// TypicalVariants returns the typical full set of benchmark variants.\n+func TypicalVariants() []Variant {\n+ variants := make([]Variant, 0, 6)\n+ for _, filesys := range []harness.FileSystemType{harness.BindFS, harness.TmpFS, harness.RootFS} {\n+ variants = append(variants, Variant{\n+ clearCache: true,\n+ fsType: filesys,\n+ })\n+ variants = append(variants, Variant{\n+ clearCache: false,\n+ fsType: filesys,\n+ })\n+ }\n+ return variants\n+}\n+\n+// RunWithDifferentFilesystems runs a\n+func RunWithDifferentFilesystems(ctx context.Context, b *testing.B, machine harness.Machine, bm FSBenchmark) {\n+ b.Helper()\n+\n+ benchmarkVariants := bm.Variants\n+ if len(benchmarkVariants) == 0 {\n+ benchmarkVariants = TypicalVariants()\n+ }\n+ for _, variant := range benchmarkVariants {\n+ pageCache := tools.Parameter{\n+ Name: \"page_cache\",\n+ Value: \"dirty\",\n+ }\n+ if variant.clearCache {\n+ pageCache.Value = \"clean\"\n+ }\n+\n+ filesystem := tools.Parameter{\n+ Name: \"filesystem\",\n+ Value: string(variant.fsType),\n+ }\n+ name, err := tools.ParametersToName(pageCache, filesystem)\n+ if err != nil {\n+ b.Fatalf(\"Failed to parse parameters: %v\", err)\n+ }\n+\n+ b.Run(name, func(b *testing.B) {\n+ // Grab a container.\n+ container := machine.GetContainer(ctx, b)\n+ cu := cleanup.Make(func() {\n+ container.CleanUp(ctx)\n+ })\n+ defer cu.Clean()\n+ mts, prefix, err := harness.MakeMount(machine, variant.fsType, &cu)\n+ if err != nil {\n+ b.Fatalf(\"Failed to make mount: %v\", err)\n+ }\n+\n+ runOpts := dockerutil.RunOpts{\n+ Image: bm.Image,\n+ Mounts: mts,\n+ }\n+\n+ // Start a container and sleep.\n+ if err := container.Spawn(ctx, runOpts, \"sleep\", \"24h\"); err != nil {\n+ b.Fatalf(\"run failed with: %v\", err)\n+ }\n+\n+ cpCmd := fmt.Sprintf(\"mkdir -p %s && cp -r %s %s/.\", prefix, bm.WorkDir, prefix)\n+ if out, err := container.Exec(ctx, dockerutil.ExecOpts{},\n+ \"/bin/sh\", \"-c\", cpCmd); err != nil {\n+ b.Fatalf(\"failed to copy directory: %v (%s)\", err, out)\n+ }\n+\n+ b.ResetTimer()\n+ b.StopTimer()\n+\n+ // Drop Caches and bazel clean should happen inside the loop as we may use\n+ // time options with b.N. (e.g. Run for an hour.)\n+ for i := 0; i < b.N; i++ {\n+ // Drop Caches for clear cache runs.\n+ if variant.clearCache {\n+ if err := harness.DropCaches(machine); err != nil {\n+ b.Skipf(\"failed to drop caches: %v. You probably need root.\", err)\n+ }\n+ }\n+\n+ b.StartTimer()\n+ got, err := container.Exec(ctx, dockerutil.ExecOpts{\n+ WorkDir: prefix + bm.WorkDir,\n+ }, bm.RunCmd...)\n+ if err != nil {\n+ b.Fatalf(\"Command %v failed with: %v logs: %s\", bm.RunCmd, err, got)\n+ }\n+ b.StopTimer()\n+\n+ if bm.WantOutput != \"\" && !strings.Contains(got, bm.WantOutput) {\n+ b.Fatalf(\"string %s not in: %s\", bm.WantOutput, got)\n+ }\n+\n+ // Clean the container in case we are doing another run.\n+ if i < b.N-1 && len(bm.CleanCmd) != 0 {\n+ if _, err = container.Exec(ctx, dockerutil.ExecOpts{\n+ WorkDir: prefix + bm.WorkDir,\n+ }, bm.CleanCmd...); err != nil {\n+ b.Fatalf(\"Cleanup command %v failed with: %v\", bm.CleanCmd, err)\n+ }\n+ }\n+ }\n+ })\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/benchmarks/fs/rubydev_test.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package rubydev_test benchmarks Ruby CI/CD-type workloads.\n+package rubydev_test\n+\n+import (\n+ \"context\"\n+ \"fmt\"\n+ \"os\"\n+ \"strings\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/test/benchmarks/fs/fsbench\"\n+ \"gvisor.dev/gvisor/test/benchmarks/harness\"\n+)\n+\n+func runRubyBenchmark(b *testing.B, bm fsbench.FSBenchmark, cleanupDirPatterns []string) {\n+ b.Helper()\n+ ctx := context.Background()\n+ machine, err := harness.GetMachine()\n+ if err != nil {\n+ b.Fatalf(\"failed to get machine: %v\", err)\n+ }\n+ defer machine.CleanUp()\n+ bm.Image = \"benchmarks/rubydev\"\n+ cleanupDirPatterns = append(cleanupDirPatterns, \"$HOME/.bundle/cache\", \"/tmp/rspec_failed_tests.txt\")\n+ bm.CleanCmd = []string{\"bash\", \"-c\", fmt.Sprintf(\"rm -rf %s\", strings.Join(cleanupDirPatterns, \" \"))}\n+ fsbench.RunWithDifferentFilesystems(ctx, b, machine, bm)\n+}\n+\n+// BenchmarkRubyNoOpTest runs a no-op Ruby test.\n+// This is the test case that Stripe used to benchmark gVisor:\n+// https://stripe.com/blog/fast-secure-builds-choose-two\n+func BenchmarkRubyNoOpTest(b *testing.B) {\n+ runRubyBenchmark(b, fsbench.FSBenchmark{\n+ Image: \"benchmarks/rubydev\",\n+ WorkDir: \"/files\",\n+ RunCmd: []string{\"ruby\", \"tc_no_op.rb\"},\n+ WantOutput: \"100% passed\",\n+ }, nil)\n+}\n+\n+// BenchmarkRubySpecTest runs a complex test suite from the Fastlane project:\n+// https://github.com/fastlane/fastlane\n+func BenchmarkRubySpecTest(b *testing.B) {\n+ runRubyBenchmark(b, fsbench.FSBenchmark{\n+ Image: \"benchmarks/rubydev\",\n+ WorkDir: \"/fastlane\",\n+ RunCmd: []string{\"bash\", \"/files/run_fastlane_tests.sh\"},\n+ WantOutput: \"3613 examples, 0 failures\",\n+ }, []string{\n+ // Fastlane tests pollute the filesystem a lot.\n+ // To find out, run `find / -exec stat -c \"%n %y\" {} \\; | sort` before and after running tests\n+ // for the first time, and diff them.\n+ \"$HOME/Library\", // Yes, even on Linux.\n+ \"$HOME/.fastlane\",\n+ \"/tmp/fastlane*\",\n+ \"/tmp/spaceship*\",\n+ \"/tmp/profile_download*\",\n+ \"/tmp/d*-*-*/*.mobileprovision\",\n+ })\n+}\n+\n+// TestMain is the main method for this package.\n+func TestMain(m *testing.M) {\n+ harness.Init()\n+ harness.SetFixedBenchmarks()\n+ os.Exit(m.Run())\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
gVisor benchmarks: Add "Ruby CI/CD experience" benchmarks. This adds two benchmarks: - A no-op Ruby unit test, based off the Stripe benchmark: https://stripe.com/blog/fast-secure-builds-choose-two - A more serious unit test suite from Fastlane, a large Ruby project: https://github.com/fastlane/fastlane PiperOrigin-RevId: 461726240
259,896
18.07.2022 18:01:57
25,200
4bc44eac9bcbf4ee402add71d5c26763a9f612d5
Multi Container: Add IsRunning() control message for the container. Adds IsRunning() control message which returns true if the container is running. Adds a test to verify the result of IsRunning().
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/control/lifecycle.go", "new_path": "pkg/sentry/control/lifecycle.go", "diff": "@@ -46,9 +46,35 @@ type Lifecycle struct {\n// namespaces.\nMountNamespacesMap map[string]*vfs.MountNamespace\n- // containerInitProcessMap is a map of container ID and the init(PID 1)\n- // threadgroup of the container.\n- containerInitProcessMap map[string]*kernel.ThreadGroup\n+ // containerMap is a map of the container id and the container.\n+ containerMap map[string]*Container\n+}\n+\n+// containerState is the state of the container.\n+type containerState int\n+\n+const (\n+ // stateCreated is the state when the container was created. It is the\n+ // initial state.\n+ stateCreated containerState = iota\n+\n+ // stateRunning is the state when the container/application is running.\n+ stateRunning\n+\n+ // stateStopped is the state when the container has exited.\n+ stateStopped\n+)\n+\n+// Container contains the set of parameters to represent a container.\n+type Container struct {\n+ // containerID.\n+ containerID string\n+\n+ // tg is the init(PID 1) threadgroup of the container.\n+ tg *kernel.ThreadGroup\n+\n+ // state is the current state of the container.\n+ state containerState\n}\n// StartContainerArgs is the set of arguments to start a container.\n@@ -104,6 +130,38 @@ func (args StartContainerArgs) String() string {\nreturn strings.Join(a, \" \")\n}\n+func (l *Lifecycle) updateContainerState(containerID string, newState containerState) error {\n+ l.mu.Lock()\n+ defer l.mu.Unlock()\n+\n+ c, ok := l.containerMap[containerID]\n+ if !ok {\n+ return fmt.Errorf(\"container %v not started\", containerID)\n+ }\n+\n+ switch newState {\n+ case stateCreated:\n+ // Impossible.\n+ panic(fmt.Sprintf(\"invalid state transition: %v => %v\", c.state, newState))\n+\n+ case stateRunning:\n+ if c.state != stateCreated {\n+ // Impossible.\n+ panic(fmt.Sprintf(\"invalid state transition: %v => %v\", c.state, newState))\n+ }\n+\n+ case stateStopped:\n+ // Valid state transition.\n+\n+ default:\n+ // Invalid new state.\n+ panic(fmt.Sprintf(\"invalid new state: %v\", newState))\n+ }\n+\n+ c.state = newState\n+ return nil\n+}\n+\n// StartContainer will start a new container in the sandbox.\nfunc (l *Lifecycle) StartContainer(args *StartContainerArgs, _ *uint32) error {\n// Import file descriptors.\n@@ -177,16 +235,24 @@ func (l *Lifecycle) StartContainer(args *StartContainerArgs, _ *uint32) error {\nreturn err\n}\n- // Start the newly created process.\n- l.Kernel.StartProcess(tg)\n- log.Infof(\"Started the new container %v \", initArgs.ContainerID)\n+ c := &Container{\n+ containerID: initArgs.ContainerID,\n+ tg: tg,\n+ state: stateCreated,\n+ }\nl.mu.Lock()\n- if l.containerInitProcessMap == nil {\n- l.containerInitProcessMap = make(map[string]*kernel.ThreadGroup)\n+ if l.containerMap == nil {\n+ l.containerMap = make(map[string]*Container)\n}\n- l.containerInitProcessMap[initArgs.ContainerID] = tg\n+ l.containerMap[initArgs.ContainerID] = c\nl.mu.Unlock()\n+\n+ // Start the newly created process.\n+ l.Kernel.StartProcess(tg)\n+ log.Infof(\"Started the new container %v \", initArgs.ContainerID)\n+\n+ l.updateContainerState(initArgs.ContainerID, stateRunning)\nreturn nil\n}\n@@ -212,11 +278,11 @@ func (l *Lifecycle) getInitContainerProcess(containerID string) (*kernel.ThreadG\nl.mu.Lock()\ndefer l.mu.Unlock()\n- tg, ok := l.containerInitProcessMap[containerID]\n+ c, ok := l.containerMap[containerID]\nif !ok {\nreturn nil, fmt.Errorf(\"container %v not started\", containerID)\n}\n- return tg, nil\n+ return c.tg, nil\n}\n// ContainerArgs is the set of arguments for container related APIs after\n@@ -235,5 +301,30 @@ func (l *Lifecycle) WaitContainer(args *ContainerArgs, waitStatus *uint32) error\ntg.WaitExited()\n*waitStatus = uint32(tg.ExitStatus())\n+ if err := l.updateContainerState(args.ContainerID, stateStopped); err != nil {\n+ return err\n+ }\n+ return nil\n+}\n+\n+// IsContainerRunning returns true if the container is running.\n+func (l *Lifecycle) IsContainerRunning(args *ContainerArgs, isRunning *bool) error {\n+ l.mu.Lock()\n+ defer l.mu.Unlock()\n+\n+ c, ok := l.containerMap[args.ContainerID]\n+ if !ok || c.state != stateRunning {\n+ return nil\n+ }\n+\n+ // The state will not be updated to \"stopped\" if the\n+ // WaitContainer(...) method is not called. In this case, check\n+ // whether the number of non-exited tasks in tg is zero to get\n+ // the correct state of the container.\n+ if c.tg.Count() == 0 {\n+ c.state = stateStopped\n+ return nil\n+ }\n+ *isRunning = true\nreturn nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Multi Container: Add IsRunning() control message for the container. - Adds IsRunning() control message which returns true if the container is running. - Adds a test to verify the result of IsRunning(). PiperOrigin-RevId: 461759652
259,878
19.07.2022 11:40:07
25,200
1ba318d72a302cf73f1712be375fb3831fa6f11e
Add security platform benefits to gvisor.dev index page. Update header title and jumbotron with security platform info. Add new benefits to index page reflecting use case value and adjust footer logo to remove blur when scaled.
[ { "change_type": "MODIFY", "old_path": "website/_includes/footer-links.html", "new_path": "website/_includes/footer-links.html", "diff": "<div class=\"col-sm-3 col-md-3\"></div>\n<div class=\"hidden-xs hidden-sm col-md-3\">\n<a href=\"https://cloud.google.com/run\">\n- <img style=\"float: right;\" src=\"/assets/logos/powered-gvisor.png\" alt=\"Powered by gVisor\"/>\n+ <img style=\"float: right; max-width: 93px; height: auto;\" src=\"/assets/logos/powered-gvisor.png\" alt=\"Powered by gVisor\"/>\n</a>\n</div>\n</div>\n" }, { "change_type": "MODIFY", "old_path": "website/_includes/header.html", "new_path": "website/_includes/header.html", "diff": "{% if page.title %}\n<title>{{ page.title }} - gVisor</title>\n{% else %}\n- <title>gVisor</title>\n+ <title>The Container Security Platform | gVisor</title>\n{% endif %}\n<link rel=\"canonical\" href=\"{{ page.url | replace:'index.html','' | prepend: site_root }}\">\n" }, { "change_type": "MODIFY", "old_path": "website/assets/logos/powered-gvisor.png", "new_path": "website/assets/logos/powered-gvisor.png", "diff": "Binary files a/website/assets/logos/powered-gvisor.png and b/website/assets/logos/powered-gvisor.png differ\n" }, { "change_type": "MODIFY", "old_path": "website/index.md", "new_path": "website/index.md", "diff": "<div class=\"row\">\n<div class=\"col-md-3\"></div>\n<div class=\"col-md-6\">\n- <p>gVisor is an <b>application kernel</b> for <b>containers</b> that provides efficient defense-in-depth anywhere.</p>\n+ <h1 style=\"color:white;\">The Container Security Platform</h1>\n+ <p>Run untrusted workloads, block container escapes, and mitigate unauthorized host access.</p>\n<p style=\"margin-top: 20px;\">\n<a class=\"btn\" href=\"/docs/user_guide/install/\">Get started&nbsp;<i class=\"fas fa-arrow-alt-circle-right ml-2\"></i></a>\n- <a class=\"btn\" href=\"/docs/\">Learn More&nbsp;<i class=\"fas fa-arrow-alt-circle-right ml-2\"></i></a>\n+ <a class=\"btn\" href=\"/docs/\">What is gVisor?&nbsp;<i class=\"fas fa-arrow-alt-circle-right ml-2\"></i></a>\n</p>\n</div>\n<div class=\"col-md-3\"></div>\n</div>\n<div class=\"container\"> <!-- Full page container. -->\n-\n<div class=\"row\">\n<div class=\"col-md-4\">\n- <h4 id=\"seamless-security\">Container-native Security <i class=\"fas fa-lock\"></i></h4>\n- <p>By providing each container with its own application kernel, gVisor\n- limits the attack surface of the host. This protection does not limit\n- functionality: gVisor runs unmodified binaries and integrates with container\n- orchestration systems, such as Docker and Kubernetes, and supports features\n- such as volumes and sidecars.</p>\n- <a class=\"button\" href=\"/docs/architecture_guide/security/\">Read More &raquo;</a>\n+ <div align=\"center\"><i class=\"fas fa-shield-alt fa-2x\"></i></div>\n+ <h3 id=\"seamless-security\">Strengthen Kubernetes Security</h3>\n+ <p>gVisor delivers an additional security boundary for containers by\n+ intercepting and monitoring workload runtime instructions in user space\n+ before they are able to reach the underlying host. This protection\n+ mitigates threats and reduces host attack surface. gVisor seamlessly\n+ integrates with existing container workflows and ecosystem.</p>\n+ <a class=\"button\" href=\"/docs/user_guide/quick_start/kubernetes/\">Learn More &raquo;</a>\n</div>\n-\n<div class=\"col-md-4\">\n- <h4 id=\"resource-efficiency\">Resource Efficiency <i class=\"fas fa-feather-alt\"></i></h4>\n- <p>Containers are efficient because workloads of different shapes and sizes\n- can be packed together by sharing host resources. gVisor uses host-native\n- abstractions, such as threads and memory mappings, to co-operate with the\n- host and enable the same resource model as native containers.</p>\n- <a class=\"button\" href=\"/docs/architecture_guide/resources/\">Read More &raquo;</a>\n+ <div align=\"center\"><i class=\"fas fa-lock fa-2x\"></i></div>\n+ <h3 id=\"seamless-security\">Protect Workloads and Infrastructure</h3>\n+ <p>Run untrusted workloads without compromising other workloads or the\n+ underlying infrastructure. Block container escapes by keeping attackers\n+ from breaking out of containers and into hosts or other containers.\n+ Mitigate privilege escalations that provide unauthorized access to other\n+ systems and services. Deliver strong isolation between containers for\n+ multitenant environments.</p>\n+ <a class=\"button\" href=\"/docs/architecture_guide/security/\">Learn More &raquo;</a>\n</div>\n-\n<div class=\"col-md-4\">\n- <h4 id=\"platform-portability\">Platform Portability <sup>&#9729;</sup>&#9729;</h4>\n- <p>Modern infrastructure spans multiple cloud services and data centers,\n- often with a mix of managed services and virtualized or traditional servers.\n- The pluggable platform architecture of gVisor allows it to run anywhere,\n- enabling consistent security policies across multiple environments without\n- having to rearchitect your infrastructure.</p>\n- <a class=\"button\" href=\"/docs/architecture_guide/platforms/\">Read More &raquo;</a>\n- </div>\n+ <div align=\"center\"><i class=\"fas fa-exclamation-triangle fa-2x\"></i></div>\n+ <h3 id=\"seamless-security\">Reduce Vulnerability and Mitigate Risk</h3>\n+ <p>Deliver a hardened Kubernetes that provides defense-in-depth\n+ runtime protection and monitoring for container workloads. Enable\n+ third-party customers to safely deliver code and highly secure services.\n+ Keep infrastructure resilient and operating during adverse cyber events.\n+ Use gVisor with threat detection engines to quickly identify threats and\n+ reduce risk with alerts.</p>\n+ <a class=\"button\" href=\"/docs/architecture_guide/security/\">Learn More &raquo;</a>\n</div>\n+ </div>\n</div> <!-- container -->\n" } ]
Go
Apache License 2.0
google/gvisor
Add security platform benefits to gvisor.dev index page. Update header title and jumbotron with security platform info. Add new benefits to index page reflecting use case value and adjust footer logo to remove blur when scaled. PiperOrigin-RevId: 461935696
259,891
19.07.2022 11:58:59
25,200
dc7675bd6ce7e8ad1183bd336e9a4defcf8ac63b
use buffered channel with signal.Notify()
[ { "change_type": "MODIFY", "old_path": "tools/tracereplay/main/main.go", "new_path": "tools/tracereplay/main/main.go", "diff": "@@ -86,7 +86,7 @@ func (c *saveCmd) Execute(_ context.Context, f *flag.FlagSet, args ...interface{\nreturn subcommands.ExitFailure\n}\n- ch := make(chan os.Signal)\n+ ch := make(chan os.Signal, 1)\nsignal.Notify(ch, os.Interrupt)\ndone := make(chan struct{})\n" } ]
Go
Apache License 2.0
google/gvisor
use buffered channel with signal.Notify() PiperOrigin-RevId: 461939747
259,853
19.07.2022 17:18:00
25,200
d9c66eb76971ea54849c6a2166e1aad91d6f6050
cpuid: cache host cpuid features HostFeatureSet() returns a fixed set that is initialized at startup. Here results fro the signal_benchmark on the kvm platform: Before: BM_FaultSignalFixup/real_time 8353 ns 8383 ns 94234 After: BM_FaultSignalFixup/real_time 6127 ns 6087 ns 111708
[ { "change_type": "MODIFY", "old_path": "pkg/cpuid/native_amd64.go", "new_path": "pkg/cpuid/native_amd64.go", "diff": "@@ -162,13 +162,13 @@ func (fs FeatureSet) query(fn cpuidFunction) (uint32, uint32, uint32, uint32) {\nreturn out.Eax, out.Ebx, out.Ecx, out.Edx\n}\n+var hostFeatureSet FeatureSet\n+\n// HostFeatureSet returns a host CPUID.\n//\n//go:nosplit\nfunc HostFeatureSet() FeatureSet {\n- return FeatureSet{\n- Function: &Native{},\n- }\n+ return hostFeatureSet\n}\nvar (\n@@ -179,7 +179,7 @@ var (\n// Reads max cpu frequency from host /proc/cpuinfo. Must run before syscall\n// filter installation. This value is used to create the fake /proc/cpuinfo\n// from a FeatureSet.\n-func init() {\n+func readMaxCPUFreq() {\ncpuinfob, err := ioutil.ReadFile(\"/proc/cpuinfo\")\nif err != nil {\n// Leave it as 0... the VDSO bails out in the same way.\n@@ -212,4 +212,13 @@ func init() {\n}\n}\nlog.Warningf(\"Could not parse /proc/cpuinfo, it is empty or does not contain cpu MHz\")\n+\n+}\n+\n+func init() {\n+ hostFeatureSet = FeatureSet{\n+ Function: &Native{},\n+ }.Fixed()\n+\n+ readMaxCPUFreq()\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/kvm_amd64_test.go", "new_path": "pkg/sentry/platform/kvm/kvm_amd64_test.go", "diff": "@@ -99,7 +99,9 @@ func nestedVirtIsOn(c *vCPU, fs *cpuid.FeatureSet) bool {\nfunc TestKernelCPUID(t *testing.T) {\nbluepillTest(t, func(c *vCPU) {\n- fs := cpuid.HostFeatureSet()\n+ fs := cpuid.FeatureSet{\n+ Function: &cpuid.Native{},\n+ }\nif nestedVirtIsOn(c, &fs) {\nt.Fatalf(\"Nested virtualization is enabled\")\n}\n" } ]
Go
Apache License 2.0
google/gvisor
cpuid: cache host cpuid features HostFeatureSet() returns a fixed set that is initialized at startup. Here results fro the signal_benchmark on the kvm platform: Before: BM_FaultSignalFixup/real_time 8353 ns 8383 ns 94234 After: BM_FaultSignalFixup/real_time 6127 ns 6087 ns 111708 PiperOrigin-RevId: 462012597
259,907
20.07.2022 14:00:21
25,200
567444310c9a2947e2827954a4455bf5864a99fc
Handle IN_DONT_FOLLOW correctly in VFS2 inotify. Added a syscall test for IN_DONT_FOLLOW as well.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/inotify.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/inotify.go", "diff": "@@ -88,7 +88,7 @@ func InotifyAddWatch(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kern\n// \"IN_DONT_FOLLOW: Don't dereference pathname if it is a symbolic link.\"\n// -- inotify(7)\nfollow := followFinalSymlink\n- if mask&linux.IN_DONT_FOLLOW == 0 {\n+ if mask&linux.IN_DONT_FOLLOW != 0 {\nfollow = nofollowFinalSymlink\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/inotify.cc", "new_path": "test/syscalls/linux/inotify.cc", "diff": "@@ -1303,8 +1303,7 @@ TEST(Inotify, SymlinkGeneratesCreateEvent) {\nconst int root_wd = ASSERT_NO_ERRNO_AND_VALUE(\nInotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));\n- ASSERT_NO_ERRNO_AND_VALUE(\n- InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));\n+ ASSERT_NO_ERRNO(InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));\nASSERT_THAT(symlink(file1.path().c_str(), link1.path().c_str()),\nSyscallSucceeds());\n@@ -1315,6 +1314,32 @@ TEST(Inotify, SymlinkGeneratesCreateEvent) {\nASSERT_THAT(events, Are({Event(IN_CREATE, root_wd, Basename(link1.path()))}));\n}\n+TEST(Inotify, SymlinkFollow) {\n+ const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ const TempPath link(NewTempAbsPath());\n+ ASSERT_THAT(symlink(file.path().c_str(), link.path().c_str()),\n+ SyscallSucceeds());\n+\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));\n+ const int file_wd = ASSERT_NO_ERRNO_AND_VALUE(\n+ InotifyAddWatch(fd.get(), link.path(), IN_ALL_EVENTS));\n+ const int link_wd = ASSERT_NO_ERRNO_AND_VALUE(\n+ InotifyAddWatch(fd.get(), link.path(), IN_ALL_EVENTS | IN_DONT_FOLLOW));\n+\n+ ASSERT_NO_ERRNO(Unlink(file.path()));\n+ ASSERT_NO_ERRNO(Unlink(link.path()));\n+\n+ const std::vector<Event> events =\n+ ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));\n+\n+ ASSERT_THAT(\n+ events,\n+ Are({Event(IN_ATTRIB, file_wd), Event(IN_DELETE_SELF, file_wd),\n+ Event(IN_IGNORED, file_wd), Event(IN_ATTRIB, link_wd),\n+ Event(IN_DELETE_SELF, link_wd), Event(IN_IGNORED, link_wd)}));\n+}\n+\nTEST(Inotify, LinkGeneratesAttribAndCreateEvents) {\n// Inotify does not work properly with hard links in gofer and overlay fs.\nSKIP_IF(IsRunningOnGvisor() &&\n" } ]
Go
Apache License 2.0
google/gvisor
Handle IN_DONT_FOLLOW correctly in VFS2 inotify. Added a syscall test for IN_DONT_FOLLOW as well. PiperOrigin-RevId: 462224328
259,907
20.07.2022 14:17:06
25,200
be38a15c16136d69ab4ac4b42811e0821bf28522
Build everything and run unit tests on ARM in Buildkite.
[ { "change_type": "MODIFY", "old_path": ".buildkite/pipeline.yaml", "new_path": ".buildkite/pipeline.yaml", "diff": "@@ -61,11 +61,19 @@ steps:\n# Build everything.\n- <<: *common\n- label: \":world_map: Build everything\"\n+ label: \":world_map: Build everything (AMD64)\"\ncommand: \"make build OPTIONS=--build_tag_filters=-nogo TARGETS=//...\"\nagents:\narch: \"amd64\"\n+ - <<: *common\n+ label: \":world_map: Build everything (ARM64)\"\n+ commands:\n+ - \"make build OPTIONS=--build_tag_filters=-nogo TARGETS=//pkg/...\"\n+ - \"make build OPTIONS=--build_tag_filters=-nogo TARGETS=//runsc/...\"\n+ agents:\n+ arch: \"arm64\"\n+\n# Check that the Go branch builds. This is not technically required, as this build is maintained\n# as a GitHub action in order to preserve this maintaince across forks. However, providing the\n# action here may provide easier debuggability and diagnosis on failure.\n@@ -151,6 +159,11 @@ steps:\nagents:\ncgroup: \"v2\"\narch: \"amd64\"\n+ - <<: *common\n+ label: \":test_tube: Unit tests (ARM64)\"\n+ command: make unit-tests\n+ agents:\n+ arch: \"arm64\"\n- <<: *common\nlabel: \":test_tube: Container tests (cgroupv1)\"\ncommand: make container-tests\n" }, { "change_type": "MODIFY", "old_path": "test/perf/linux/signal_benchmark.cc", "new_path": "test/perf/linux/signal_benchmark.cc", "diff": "@@ -25,6 +25,8 @@ namespace testing {\nnamespace {\n+#ifdef __x86_64__\n+\nvoid FixupHandler(int sig, siginfo_t* si, void* void_ctx) {\nstatic unsigned int dataval = 0;\n@@ -55,6 +57,8 @@ void BM_FaultSignalFixup(benchmark::State& state) {\nBENCHMARK(BM_FaultSignalFixup)->UseRealTime();\n+#endif // __x86_64__\n+\n} // namespace\n} // namespace testing\n" } ]
Go
Apache License 2.0
google/gvisor
Build everything and run unit tests on ARM in Buildkite. PiperOrigin-RevId: 462228233
259,853
21.07.2022 13:18:11
25,200
796050f1dac9349a4acbf776c0f5dcb763dab274
kvm: limit number of vCPU-s We see a regression of the startup benchmark. The main reason is that the maximum number of vCPUs in the kernel has been increased from 256 to 1024. In most cases, we don't need so many vCPU-s.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine_amd64.go", "new_path": "pkg/sentry/platform/kvm/machine_amd64.go", "diff": "@@ -21,6 +21,7 @@ import (\n\"fmt\"\n\"math/big\"\n\"reflect\"\n+ \"runtime\"\n\"runtime/debug\"\n\"golang.org/x/sys/unix\"\n@@ -478,6 +479,16 @@ func (m *machine) getMaxVCPU() {\n} else {\nm.maxVCPUs = int(maxVCPUs)\n}\n+\n+ // The goal here is to avoid vCPU contentions for reasonable workloads.\n+ // But \"reasonable\" isn't defined well in this case. Let's say that CPU\n+ // overcommit with factor 2 is still acceptable. We allocate a set of\n+ // vCPU for each goruntime processor (P) and two sets of vCPUs to run\n+ // user code.\n+ rCPUs := runtime.GOMAXPROCS(0)\n+ if 3*rCPUs < m.maxVCPUs {\n+ m.maxVCPUs = 3 * rCPUs\n+ }\n}\nfunc archPhysicalRegions(physicalRegions []physicalRegion) []physicalRegion {\n" } ]
Go
Apache License 2.0
google/gvisor
kvm: limit number of vCPU-s We see a regression of the startup benchmark. The main reason is that the maximum number of vCPUs in the kernel has been increased from 256 to 1024. In most cases, we don't need so many vCPU-s. PiperOrigin-RevId: 462455491
259,891
21.07.2022 18:51:04
25,200
c8f981f9b21e591f1057a68a3a613ce2485bea12
benchmarks: add --disable-linux-gro
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/tcp/tcp_benchmark.sh", "new_path": "test/benchmarks/tcp/tcp_benchmark.sh", "diff": "@@ -42,6 +42,7 @@ duration=30 # 30s is enough time to consistent results (experimental\nhelper_dir=$(dirname $0)\nnetstack_opts=\ndisable_linux_gso=\n+disable_linux_gro=\nnum_client_threads=1\n# Check for netem support.\n@@ -136,6 +137,9 @@ while [ $# -gt 0 ]; do\n--disable-linux-gso)\ndisable_linux_gso=1\n;;\n+ --disable-linux-gro)\n+ disable_linux_gro=1\n+ ;;\n--num-client-threads)\nshift\nnum_client_threads=$1\n@@ -165,7 +169,8 @@ while [ $# -gt 0 ]; do\necho \" --duplicate set the duplicate probability (%)\"\necho \" --helpers set the helper directory\"\necho \" --num-client-threads number of parallel client threads to run\"\n- echo \" --disable-linux-gso disable segmentation offload in the Linux network stack\"\n+ echo \" --disable-linux-gso disable segmentation offload (TSO, GSO, GRO) in the Linux network stack\"\n+ echo \" --disable-linux-gro disable GRO in the Linux network stack\"\necho \"\"\necho \"The output will of the script will be:\"\necho \" <throughput> <client-cpu-usage> <server-cpu-usage>\"\n@@ -322,12 +327,16 @@ ${nsjoin_binary} /tmp/client.netns ip addr add ${client_addr}/${mask} dev client\n${nsjoin_binary} /tmp/server.netns ip addr add ${server_addr}/${mask} dev server.0\nif [ \"${disable_linux_gso}\" == \"1\" ]; then\n${nsjoin_binary} /tmp/client.netns ethtool -K client.0 tso off\n- ${nsjoin_binary} /tmp/client.netns ethtool -K client.0 gro off\n${nsjoin_binary} /tmp/client.netns ethtool -K client.0 gso off\n+ ${nsjoin_binary} /tmp/client.netns ethtool -K client.0 gro off\n${nsjoin_binary} /tmp/server.netns ethtool -K server.0 tso off\n${nsjoin_binary} /tmp/server.netns ethtool -K server.0 gso off\n${nsjoin_binary} /tmp/server.netns ethtool -K server.0 gro off\nfi\n+if [ \"${disable_linux_gro}\" == \"1\" ]; then\n+ ${nsjoin_binary} /tmp/client.netns ethtool -K client.0 gro off\n+ ${nsjoin_binary} /tmp/server.netns ethtool -K server.0 gro off\n+fi\n${nsjoin_binary} /tmp/client.netns ip link set client.0 up\n${nsjoin_binary} /tmp/client.netns ip link set lo up\n${nsjoin_binary} /tmp/server.netns ip link set server.0 up\n" } ]
Go
Apache License 2.0
google/gvisor
benchmarks: add --disable-linux-gro PiperOrigin-RevId: 462516480
259,891
22.07.2022 16:32:11
25,200
64299b5b226f20cffd8afaa3f3d0b8fc2a070476
remove references to nonexistent directory
[ { "change_type": "MODIFY", "old_path": "test/runner/gtest/gtest.go", "new_path": "test/runner/gtest/gtest.go", "diff": "@@ -141,7 +141,7 @@ func ParseTestCases(testBin string, benchmarks bool, extraArgs ...string) ([]Tes\nreturn t, nil\n}\n-// ParseBenchmarks returns each benchmark in a third_party/benchmark binary's list as a single test case.\n+// ParseBenchmarks returns each benchmark in the binary's list as a single test case.\nfunc ParseBenchmarks(binary string, extraArgs ...string) ([]TestCase, error) {\nvar t []TestCase\nargs := append([]string{listBenchmarkFlag}, extraArgs...)\n" }, { "change_type": "MODIFY", "old_path": "test/runtimes/README.md", "new_path": "test/runtimes/README.md", "diff": "@@ -68,7 +68,7 @@ To bump the version of an existing runtime test:\nThis will likely look similar to the older version, so start by copying the\nolder one. Update any packages or downloaded urls to point to the new\nversion. Test building the image with `docker build\n- third_party/gvisor/images/runtime/<new_runtime>`\n+ images/runtime/<new_runtime>`\n2. Create a new [`runtime_test`](BUILD) target. The `name` field must be the\ndirctory name for the Docker image you created in Step 1.\n" }, { "change_type": "MODIFY", "old_path": "webhook/BUILD", "new_path": "webhook/BUILD", "diff": "@@ -21,7 +21,7 @@ pkg_tar(\nname = \"files\",\nsrcs = [\":webhook\"],\nextension = \"tgz\",\n- strip_prefix = \"/third_party/gvisor/webhook\",\n+ strip_prefix = \"/webhook\",\n)\ngo_binary(\n" } ]
Go
Apache License 2.0
google/gvisor
remove references to nonexistent directory PiperOrigin-RevId: 462728462
259,907
25.07.2022 11:32:00
25,200
49d88e92ed25cc1996ce504d6f2b7de4da08da0d
Do not debug log read/write buffers in lisafs. These logs are not helpful and just make logs very noisy.
[ { "change_type": "MODIFY", "old_path": "pkg/lisafs/message.go", "new_path": "pkg/lisafs/message.go", "diff": "@@ -857,7 +857,7 @@ type PReadResp struct {\n// String implements fmt.Stringer.String.\nfunc (r *PReadResp) String() string {\n- return fmt.Sprintf(\"PReadResp{NumBytes: %d, Buf: %v}\", r.NumBytes, r.Buf)\n+ return fmt.Sprintf(\"PReadResp{NumBytes: %d, Buf: [...%d bytes...]}\", r.NumBytes, len(r.Buf))\n}\n// SizeBytes implements marshal.Marshallable.SizeBytes.\n@@ -894,7 +894,7 @@ type PWriteReq struct {\n// String implements fmt.Stringer.String.\nfunc (w *PWriteReq) String() string {\n- return fmt.Sprintf(\"PWriteReq{Offset: %d, FD: %d, NumBytes: %d, Buf: %v}\", w.Offset, w.FD, w.NumBytes, w.Buf)\n+ return fmt.Sprintf(\"PWriteReq{Offset: %d, FD: %d, NumBytes: %d, Buf: [...%d bytes...]}\", w.Offset, w.FD, w.NumBytes, len(w.Buf))\n}\n// SizeBytes implements marshal.Marshallable.SizeBytes.\n" } ]
Go
Apache License 2.0
google/gvisor
Do not debug log read/write buffers in lisafs. These logs are not helpful and just make logs very noisy. PiperOrigin-RevId: 463136631
259,909
25.07.2022 13:19:30
25,200
d542d45a28e3d759b20e33c36f0f577ed01cee74
Adjust batch size in fifo qdisc to match the fdbased batch size. These two are frequently used together, so this change slightly optimizes the number of write syscalls.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/fdbased/endpoint.go", "new_path": "pkg/tcpip/link/fdbased/endpoint.go", "diff": "@@ -66,6 +66,11 @@ type linkDispatcher interface {\ntype PacketDispatchMode int\nconst (\n+ // BatchSize is the number of packets to write in each syscall. It is 47\n+ // because when GvisorGSO is in use then a single 65KB TCP segment can get\n+ // split into 46 segments of 1420 bytes and a single 216 byte segment.\n+ BatchSize = 47\n+\n// Readv is the default dispatch mode and is the least performant of the\n// dispatch options but the one that is supported by all underlying FD\n// types.\n@@ -670,11 +675,7 @@ func (e *endpoint) sendBatch(batchFDInfo fdInfo, pkts []*stack.PacketBuffer) (in\n// - pkt.NetworkProtocolNumber\nfunc (e *endpoint) WritePackets(pkts stack.PacketBufferList) (int, tcpip.Error) {\n// Preallocate to avoid repeated reallocation as we append to batch.\n- // batchSz is 47 because when GvisorGSO is in use then a single 65KB TCP\n- // segment can get split into 46 segments of 1420 bytes and a single 216\n- // byte segment.\n- const batchSz = 47\n- batch := make([]*stack.PacketBuffer, 0, batchSz)\n+ batch := make([]*stack.PacketBuffer, 0, BatchSize)\nbatchFDInfo := fdInfo{fd: -1, isSocket: false}\nsentPackets := 0\nfor _, pkt := range pkts.AsSlice() {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/qdisc/fifo/fifo.go", "new_path": "pkg/tcpip/link/qdisc/fifo/fifo.go", "diff": "@@ -28,9 +28,11 @@ import (\nvar _ stack.QueueingDiscipline = (*discipline)(nil)\nconst (\n- // BatchSize represents the number of packets written to the\n- // lower link endpoint during calls to WritePackets.\n- BatchSize = 32\n+ // BatchSize is the number of packets to write in each syscall. It is 47\n+ // because when GvisorGSO is in use then a single 65KB TCP segment can get\n+ // split into 46 segments of 1420 bytes and a single 216 byte segment.\n+ BatchSize = 47\n+\nqDiscClosed = 1\n)\n" } ]
Go
Apache License 2.0
google/gvisor
Adjust batch size in fifo qdisc to match the fdbased batch size. These two are frequently used together, so this change slightly optimizes the number of write syscalls. PiperOrigin-RevId: 463161851
259,891
26.07.2022 11:50:34
25,200
d894c1d09b9cbcf9723be5bb76710cd071db367a
add clang to default image clang will be used to compile BPF.
[ { "change_type": "MODIFY", "old_path": "images/default/Dockerfile", "new_path": "images/default/Dockerfile", "diff": "@@ -7,7 +7,11 @@ RUN apt-get update && apt-get install -y curl gnupg2 git \\\nopenjdk-11-jdk-headless zip unzip \\\napt-transport-https ca-certificates gnupg-agent \\\nsoftware-properties-common \\\n- pkg-config libffi-dev patch diffutils libssl-dev iptables kmod\n+ pkg-config libffi-dev patch diffutils libssl-dev iptables kmod \\\n+ clang\n+\n+# For compiling BPF with clang.\n+RUN ln -s /usr/include/$(uname -m)-linux-gnu/asm /usr/include/asm\n# Install Docker client for the website build.\nRUN curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -\n" } ]
Go
Apache License 2.0
google/gvisor
add clang to default image clang will be used to compile BPF. PiperOrigin-RevId: 463392266
259,975
26.07.2022 11:56:30
25,200
b18db49e9dbd96edc04beb5338d8af99341d3d4e
[benchmarks] Remove broken runsc benchmark. This has been replaced by the gRPC build benchmark which is below the removed BuildRunsc benchmark.
[ { "change_type": "DELETE", "old_path": "images/benchmarks/runsc/Dockerfile.x86_64", "new_path": null, "diff": "-FROM ubuntu:18.04\n-\n-RUN set -x \\\n- && apt-get update \\\n- && apt-get install -y \\\n- wget \\\n- git \\\n- pkg-config \\\n- zip \\\n- g++ \\\n- zlib1g-dev \\\n- unzip \\\n- python-minimal \\\n- python3 \\\n- python3-pip \\\n- && rm -rf /var/lib/apt/lists/*\n-\n-RUN wget https://github.com/bazelbuild/bazel/releases/download/3.4.1/bazel-3.4.1-installer-linux-x86_64.sh\n-RUN chmod +x bazel-3.4.1-installer-linux-x86_64.sh\n-RUN ./bazel-3.4.1-installer-linux-x86_64.sh\n-\n-# Download release-20200601.0\n-RUN mkdir gvisor && cd gvisor \\\n- && git init && git remote add origin https://github.com/google/gvisor.git \\\n- && git fetch --depth 1 origin a9b47390c821942d60784e308f681f213645049c && git checkout FETCH_HEAD\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/fs/bazel_test.go", "new_path": "test/benchmarks/fs/bazel_test.go", "diff": "@@ -29,12 +29,6 @@ func BenchmarkBuildABSL(b *testing.B) {\nrunBuildBenchmark(b, \"benchmarks/absl\", \"/abseil-cpp\", \"absl/base/...\")\n}\n-// Note: CleanCache versions of this test require running with root permissions.\n-// Note: This test takes on the order of 10m per permutation for runsc on kvm.\n-func BenchmarkBuildRunsc(b *testing.B) {\n- runBuildBenchmark(b, \"benchmarks/runsc\", \"/gvisor\", \"runsc:runsc\")\n-}\n-\n// Note: CleanCache versions of this test require running with root permissions.\n// Note: This test takes on the order of 6m per permutation for runsc on kvm.\nfunc BenchmarkBuildGRPC(b *testing.B) {\n" } ]
Go
Apache License 2.0
google/gvisor
[benchmarks] Remove broken runsc benchmark. This has been replaced by the gRPC build benchmark which is below the removed BuildRunsc benchmark. PiperOrigin-RevId: 463393704
259,909
26.07.2022 14:57:53
25,200
c689b5513cb7f831dfd126c8920d2b87fa331d99
Change buffer pooling to be false by default for runsc.
[ { "change_type": "MODIFY", "old_path": "runsc/config/flags.go", "new_path": "runsc/config/flags.go", "diff": "@@ -96,7 +96,7 @@ func RegisterFlags(flagSet *flag.FlagSet) {\nflagSet.Bool(\"rx-checksum-offload\", true, \"enable RX checksum offload.\")\nflagSet.Var(queueingDisciplinePtr(QDiscFIFO), \"qdisc\", \"specifies which queueing discipline to apply by default to the non loopback nics used by the sandbox.\")\nflagSet.Int(\"num-network-channels\", 1, \"number of underlying channels(FDs) to use for network link endpoints.\")\n- flagSet.Bool(\"buffer-pooling\", true, \"enable allocation of buffers from a shared pool instead of the heap.\")\n+ flagSet.Bool(\"buffer-pooling\", false, \"enable allocation of buffers from a shared pool instead of the heap.\")\n// Test flags, not to be used outside tests, ever.\nflagSet.Bool(\"TESTONLY-unsafe-nonroot\", false, \"TEST ONLY; do not ever use! This skips many security measures that isolate the host from the sandbox.\")\n" } ]
Go
Apache License 2.0
google/gvisor
Change buffer pooling to be false by default for runsc. PiperOrigin-RevId: 463434661
259,853
26.07.2022 15:42:32
25,200
8e4cb261486ad84bc5657b1cee0288018f693d01
Add support of rootless containers * support podmand rootless containers * support docker rootless containers Fixes
[ { "change_type": "MODIFY", "old_path": ".buildkite/pipeline.yaml", "new_path": ".buildkite/pipeline.yaml", "diff": "@@ -280,6 +280,12 @@ steps:\nagents:\ncgroup: \"v2\"\nos: \"ubuntu\"\n+ - <<: *common\n+ label: \":podman: Podman\"\n+ command: sudo ./test/podman/run.sh\n+ agents:\n+ cgroup: \"v2\"\n+ os: \"ubuntu\"\n# Check the website builds.\n- <<: *common\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/do.go", "new_path": "runsc/cmd/do.go", "diff": "@@ -48,6 +48,8 @@ type Do struct {\nip string\nquiet bool\noverlay bool\n+ uidMap idMapSlice\n+ gidMap idMapSlice\n}\n// Name implements subcommands.Command.Name.\n@@ -72,6 +74,44 @@ used for testing only.\n`\n}\n+type idMapSlice []specs.LinuxIDMapping\n+\n+// String implements flag.Value.String.\n+func (is *idMapSlice) String() string {\n+ return fmt.Sprintf(\"%#v\", is)\n+}\n+\n+// Get implements flag.Value.Get.\n+func (is *idMapSlice) Get() interface{} {\n+ return is\n+}\n+\n+// Set implements flag.Value.Set.\n+func (is *idMapSlice) Set(s string) error {\n+ fs := strings.Fields(s)\n+ if len(fs) != 3 {\n+ return fmt.Errorf(\"invalid mapping: %s\", s)\n+ }\n+ var cid, hid, size int\n+ var err error\n+ if cid, err = strconv.Atoi(fs[0]); err != nil {\n+ return fmt.Errorf(\"invalid mapping: %s\", s)\n+ }\n+ if hid, err = strconv.Atoi(fs[1]); err != nil {\n+ return fmt.Errorf(\"invalid mapping: %s\", s)\n+ }\n+ if size, err = strconv.Atoi(fs[2]); err != nil {\n+ return fmt.Errorf(\"invalid mapping: %s\", s)\n+ }\n+ m := specs.LinuxIDMapping{\n+ ContainerID: uint32(cid),\n+ HostID: uint32(hid),\n+ Size: uint32(size),\n+ }\n+ *is = append(*is, m)\n+ return nil\n+}\n+\n// SetFlags implements subcommands.Command.SetFlags.\nfunc (c *Do) SetFlags(f *flag.FlagSet) {\nf.StringVar(&c.root, \"root\", \"/\", `path to the root directory, defaults to \"/\"`)\n@@ -79,6 +119,8 @@ func (c *Do) SetFlags(f *flag.FlagSet) {\nf.StringVar(&c.ip, \"ip\", \"192.168.10.2\", \"IPv4 address for the sandbox\")\nf.BoolVar(&c.quiet, \"quiet\", false, \"suppress runsc messages to stdout. Application output is still sent to stdout and stderr\")\nf.BoolVar(&c.overlay, \"force-overlay\", true, \"use an overlay. WARNING: disabling gives the command write access to the host\")\n+ f.Var(&c.uidMap, \"uid-map\", \"Add a user id mapping [ContainerID, HostID, Size]\")\n+ f.Var(&c.gidMap, \"gid-map\", \"Add a group id mapping [ContainerID, HostID, Size]\")\n}\n// Execute implements subcommands.Command.Execute.\n@@ -129,6 +171,12 @@ func (c *Do) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}) su\ncid := fmt.Sprintf(\"runsc-%06d\", rand.Int31n(1000000))\n+ if c.uidMap != nil || c.gidMap != nil {\n+ addNamespace(spec, specs.LinuxNamespace{Type: specs.UserNamespace})\n+ spec.Linux.UIDMappings = c.uidMap\n+ spec.Linux.GIDMappings = c.gidMap\n+ }\n+\nif conf.Network == config.NetworkNone {\naddNamespace(spec, specs.LinuxNamespace{Type: specs.NetworkNamespace})\n} else if conf.Rootless {\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/gofer.go", "new_path": "runsc/cmd/gofer.go", "diff": "@@ -18,8 +18,10 @@ import (\n\"context\"\n\"encoding/json\"\n\"fmt\"\n+ \"io\"\n\"os\"\n\"path/filepath\"\n+ \"runtime\"\n\"runtime/debug\"\n\"strings\"\n@@ -65,6 +67,7 @@ type Gofer struct {\nspecFD int\nmountsFD int\n+ syncUsernsFD int\n}\n// Name implements subcommands.Command.\n@@ -92,6 +95,7 @@ func (g *Gofer) SetFlags(f *flag.FlagSet) {\nf.Var(&g.ioFDs, \"io-fds\", \"list of FDs to connect gofer servers. They must follow this order: root first, then mounts as defined in the spec\")\nf.IntVar(&g.specFD, \"spec-fd\", -1, \"required fd with the container spec\")\nf.IntVar(&g.mountsFD, \"mounts-fd\", -1, \"mountsFD is the file descriptor to write list of mounts after they have been resolved (direct paths, no symlinks).\")\n+ f.IntVar(&g.syncUsernsFD, \"sync-userns-fd\", -1, \"file descriptor used to synchronize rootless user namespace initialization.\")\n}\n// Execute implements subcommands.Command.\n@@ -113,6 +117,26 @@ func (g *Gofer) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nutil.Fatalf(\"reading spec: %v\", err)\n}\n+ if g.syncUsernsFD >= 0 {\n+ f := os.NewFile(uintptr(g.syncUsernsFD), \"sync FD\")\n+ defer f.Close()\n+ var b [1]byte\n+ if n, err := f.Read(b[:]); n != 0 || err != io.EOF {\n+ util.Fatalf(\"failed to sync: %v: %v\", n, err)\n+ }\n+\n+ f.Close()\n+ // SETUID changes UID on the current system thread, so we have\n+ // to re-execute current binary.\n+ runtime.LockOSThread()\n+ if _, _, errno := unix.RawSyscall(unix.SYS_SETUID, 0, 0, 0); errno != 0 {\n+ util.Fatalf(\"failed to set UID: %v\", errno)\n+ }\n+ if _, _, errno := unix.RawSyscall(unix.SYS_SETGID, 0, 0, 0); errno != 0 {\n+ util.Fatalf(\"failed to set GID: %v\", errno)\n+ }\n+ }\n+\nif g.setUpRoot {\nif err := setupRootFS(spec, conf); err != nil {\nutil.Fatalf(\"Error setting up root FS: %v\", err)\n@@ -122,11 +146,16 @@ func (g *Gofer) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n// Disable caps when calling myself again.\n// Note: minimal argument handling for the default case to keep it simple.\nargs := os.Args\n- args = append(args, \"--apply-caps=false\", \"--setup-root=false\")\n+ args = append(args, \"--apply-caps=false\", \"--setup-root=false\", \"--sync-userns-fd=-1\")\nutil.Fatalf(\"setCapsAndCallSelf(%v, %v): %v\", args, goferCaps, setCapsAndCallSelf(args, goferCaps))\npanic(\"unreachable\")\n}\n+ if g.syncUsernsFD >= 0 {\n+ // syncUsernsFD is set, but runsc hasn't been re-exeuted with a new UID and GID.\n+ // We expcec that setCapsAndCallSelfsetCapsAndCallSelf has to be called in this case.\n+ panic(\"unreachable\")\n+ }\n// At this point we won't re-execute, so it's safe to limit via rlimits. Any\n// limit >= 0 works. If the limit is lower than the current number of open\n// files, then Setrlimit will succeed, and the next open will fail.\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container.go", "new_path": "runsc/container/container.go", "diff": "@@ -971,9 +971,11 @@ func (c *Container) createGoferProcess(spec *specs.Spec, conf *config.Config, bu\n{Type: specs.UTSNamespace},\n}\n+ rootlessEUID := unix.Getuid() != 0\n// Setup any uid/gid mappings, and create or join the configured user\n// namespace so the gofer's view of the filesystem aligns with the\n// users in the sandbox.\n+ if !rootlessEUID {\nuserNS := specutils.FilterNS([]specs.LinuxNamespaceType{specs.UserNamespace}, spec)\nnss = append(nss, userNS...)\nspecutils.SetUIDGIDMappings(cmd, spec)\n@@ -981,6 +983,37 @@ func (c *Container) createGoferProcess(spec *specs.Spec, conf *config.Config, bu\n// We need to set UID and GID to have capabilities in a new user namespace.\ncmd.SysProcAttr.Credential = &syscall.Credential{Uid: 0, Gid: 0}\n}\n+ } else {\n+ userNS := specutils.FilterNS([]specs.LinuxNamespaceType{specs.UserNamespace}, spec)\n+ if len(userNS) == 0 {\n+ return nil, nil, fmt.Errorf(\"unable to run a rootless container without userns\")\n+ }\n+ fds, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0)\n+ if err != nil {\n+ return nil, nil, err\n+ }\n+ syncFile := os.NewFile(uintptr(fds[0]), \"sync FD\")\n+ defer syncFile.Close()\n+\n+ f := os.NewFile(uintptr(fds[1]), \"sync other FD\")\n+ donations.DonateAndClose(\"sync-userns-fd\", f)\n+ if cmd.SysProcAttr == nil {\n+ cmd.SysProcAttr = &unix.SysProcAttr{}\n+ }\n+ cmd.SysProcAttr.AmbientCaps = []uintptr{\n+ unix.CAP_CHOWN,\n+ unix.CAP_DAC_OVERRIDE,\n+ unix.CAP_DAC_READ_SEARCH,\n+ unix.CAP_FOWNER,\n+ unix.CAP_FSETID,\n+ unix.CAP_SYS_CHROOT,\n+ unix.CAP_SETUID,\n+ unix.CAP_SETGID,\n+ unix.CAP_SYS_ADMIN,\n+ unix.CAP_SETPCAP,\n+ }\n+ nss = append(nss, specs.LinuxNamespace{Type: specs.UserNamespace})\n+ }\ndonations.Transfer(cmd, nextFD)\n@@ -990,6 +1023,43 @@ func (c *Container) createGoferProcess(spec *specs.Spec, conf *config.Config, bu\nif err := specutils.StartInNS(cmd, nss); err != nil {\nreturn nil, nil, fmt.Errorf(\"gofer: %v\", err)\n}\n+\n+ if rootlessEUID {\n+ log.Debugf(\"Setting user mappings\")\n+ args := []string{strconv.Itoa(cmd.Process.Pid)}\n+ for _, idMap := range spec.Linux.UIDMappings {\n+ log.Infof(\"Mapping host uid %d to container uid %d (size=%d)\",\n+ idMap.HostID, idMap.ContainerID, idMap.Size)\n+ args = append(args,\n+ strconv.Itoa(int(idMap.ContainerID)),\n+ strconv.Itoa(int(idMap.HostID)),\n+ strconv.Itoa(int(idMap.Size)),\n+ )\n+ }\n+\n+ out, err := exec.Command(\"newuidmap\", args...).CombinedOutput()\n+ log.Debugf(\"newuidmap: %#v\\n%s\", args, out)\n+ if err != nil {\n+ return nil, nil, fmt.Errorf(\"newuidmap failed: %w\", err)\n+ }\n+\n+ args = []string{strconv.Itoa(cmd.Process.Pid)}\n+ for _, idMap := range spec.Linux.GIDMappings {\n+ log.Infof(\"Mapping host uid %d to container uid %d (size=%d)\",\n+ idMap.HostID, idMap.ContainerID, idMap.Size)\n+ args = append(args,\n+ strconv.Itoa(int(idMap.ContainerID)),\n+ strconv.Itoa(int(idMap.HostID)),\n+ strconv.Itoa(int(idMap.Size)),\n+ )\n+ }\n+ out, err = exec.Command(\"newgidmap\", args...).CombinedOutput()\n+ log.Debugf(\"newgidmap: %#v\\n%s\", args, out)\n+ if err != nil {\n+ return nil, nil, fmt.Errorf(\"newgidmap failed: %w\", err)\n+ }\n+ }\n+\nlog.Infof(\"Gofer started, PID: %d\", cmd.Process.Pid)\nc.GoferPid = cmd.Process.Pid\nc.goferIsChild = true\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/sandbox.go", "new_path": "runsc/sandbox/sandbox.go", "diff": "@@ -18,6 +18,7 @@ package sandbox\nimport (\n\"context\"\n\"encoding/json\"\n+ \"errors\"\n\"fmt\"\n\"io\"\n\"math\"\n@@ -717,18 +718,19 @@ func (s *Sandbox) createSandboxProcess(conf *config.Config, args *Args, startSyn\nreturn fmt.Errorf(\"can't run sandbox process in minimal chroot since we don't have CAP_SYS_ADMIN\")\n}\n} else {\n+ rootlessEUID := unix.Getuid() != 0\n// If we have CAP_SETUID and CAP_SETGID, then we can also run\n// as user nobody.\nif conf.TestOnlyAllowRunAsCurrentUserWithoutChroot {\nlog.Warningf(\"Running sandbox in test mode as current user (uid=%d gid=%d). This is only safe in tests!\", os.Getuid(), os.Getgid())\nlog.Warningf(\"Running sandbox in test mode without chroot. This is only safe in tests!\")\n- } else if specutils.HasCapabilities(capability.CAP_SETUID, capability.CAP_SETGID) {\n+ } else if rootlessEUID || specutils.HasCapabilities(capability.CAP_SETUID, capability.CAP_SETGID) {\nlog.Infof(\"Sandbox will be started in new user namespace\")\nnss = append(nss, specs.LinuxNamespace{Type: specs.UserNamespace})\ncmd.Args = append(cmd.Args, \"--setup-root\")\nconst nobody = 65534\n- if conf.Rootless {\n+ if rootlessEUID || conf.Rootless {\nlog.Infof(\"Rootless mode: sandbox will run as nobody inside user namespace, mapped to the current user, uid: %d, gid: %d\", os.Getuid(), os.Getgid())\n} else {\n// Map nobody in the new namespace to nobody in the parent namespace.\n@@ -1419,6 +1421,10 @@ func (s *Sandbox) configureStdios(conf *config.Config, stdios []*os.File) error\nfor _, file := range stdios {\nlog.Debugf(\"Changing %q ownership to %d/%d\", file.Name(), s.UID, s.GID)\nif err := file.Chown(s.UID, s.GID); err != nil {\n+ if errors.Is(err, unix.EINVAL) || errors.Is(err, unix.EPERM) || errors.Is(err, unix.EROFS) {\n+ log.Warningf(\"can't change an owner of %s: %s\", file.Name(), err)\n+ continue\n+ }\nreturn err\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/specutils/namespace.go", "new_path": "runsc/specutils/namespace.go", "diff": "@@ -119,7 +119,7 @@ func setNS(fd, nsType uintptr) error {\n// that will restore the namespace to the original value.\n//\n// Preconditions: Must be called with os thread locked.\n-func ApplyNS(ns specs.LinuxNamespace) (func(), error) {\n+func ApplyNS(ns specs.LinuxNamespace) (func() error, error) {\nlog.Infof(\"Applying namespace %v at path %q\", ns.Type, ns.Path)\nnewNS, err := os.Open(ns.Path)\nif err != nil {\n@@ -140,27 +140,49 @@ func ApplyNS(ns specs.LinuxNamespace) (func(), error) {\noldNS.Close()\nreturn nil, fmt.Errorf(\"error setting namespace of type %v and path %q: %v\", ns.Type, ns.Path, err)\n}\n- return func() {\n+ return func() error {\nlog.Infof(\"Restoring namespace %v\", ns.Type)\ndefer oldNS.Close()\nif err := setNS(oldNS.Fd(), flag); err != nil {\n- panic(fmt.Sprintf(\"error restoring namespace: of type %v: %v\", ns.Type, err))\n+ return fmt.Errorf(\"error restoring namespace: of type %v: %v\", ns.Type, err)\n}\n+ return nil\n}, nil\n}\n// StartInNS joins or creates the given namespaces and calls cmd.Start before\n// restoring the namespaces to the original values.\nfunc StartInNS(cmd *exec.Cmd, nss []specs.LinuxNamespace) error {\n- // We are about to setup namespaces, which requires the os thread being\n- // locked so that Go doesn't change the thread out from under us.\n+ errChan := make(chan error)\n+ go func() {\nruntime.LockOSThread()\ndefer runtime.UnlockOSThread()\n+ rstFuncs, err := startInNS(cmd, nss)\n+ errChan <- err\n+ for _, rstFunc := range rstFuncs {\n+ err := rstFunc()\n+ if err == nil {\n+ continue\n+ }\n+\n+ // One or more namespaces have not been restored, but\n+ // we can't destroy the current system thread, because\n+ // a child process is execited with Pdeathsig.\n+ log.Debugf(\"Block the current system thread due to: %s\", err)\n+ c := make(chan interface{})\n+ <-c\n+ }\n+ }()\n+ return <-errChan\n+}\n+\n+func startInNS(cmd *exec.Cmd, nss []specs.LinuxNamespace) ([]func() error, error) {\nif cmd.SysProcAttr == nil {\ncmd.SysProcAttr = &unix.SysProcAttr{}\n}\n+ var deferFuncs []func() error\nfor _, ns := range nss {\nif ns.Path == \"\" {\n// No path. Just set a flag to create a new namespace.\n@@ -171,12 +193,12 @@ func StartInNS(cmd *exec.Cmd, nss []specs.LinuxNamespace) error {\n// before exiting.\nrestoreNS, err := ApplyNS(ns)\nif err != nil {\n- return err\n+ return deferFuncs, err\n}\n- defer restoreNS()\n+ deferFuncs = append(deferFuncs, restoreNS)\n}\n- return cmd.Start()\n+ return deferFuncs, cmd.Start()\n}\n// SetUIDGIDMappings sets the given uid/gid mappings from the spec on the cmd.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/podman/run.sh", "diff": "+#!/bin/bash\n+\n+# Copyright 2022 The gVisor Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+set -u -x -e -o pipefail\n+\n+export DEBIAN_FRONTEND=noninteractive\n+sudo -E apt-get install -qy podman\n+\n+test_dir=\"$(mktemp -d /tmp/gvisor-podman.XXXXXX)\"\n+podman_runtime=\"${test_dir}/runsc.podman\"\n+\n+cleanup() {\n+ rm -rf \"${test_dir}\"\n+}\n+trap cleanup EXIT\n+\n+make copy TARGETS=runsc DESTINATION=\"${test_dir}\"\n+cat > \"${podman_runtime}\" <<EOF\n+#!/bin/bash\n+\n+exec $test_dir/runsc --ignore-cgroups --debug --debug-log ${test_dir}/runsc.log \"\\$@\"\n+EOF\n+chmod ugo+x \"${podman_runtime}\"\n+chmod ugo+x \"${test_dir}/runsc\"\n+chmod ugo+xwr \"${test_dir}\"\n+grep podman-testuser /etc/passwd || \\\n+adduser --disabled-login --disabled-password podman-testuser < /dev/null\n+(\n+ cd /\n+ sudo -u podman-testuser podman run --runtime \"${podman_runtime}\" alpine echo \"Hello, world\"\n+)\n" } ]
Go
Apache License 2.0
google/gvisor
Add support of rootless containers * support podmand rootless containers * support docker rootless containers Fixes #311 PiperOrigin-RevId: 463444736
259,909
27.07.2022 16:14:07
25,200
502cc29f872edf3524486d40ebca149b30c85d30
Add a method that returns an owned copy of the data in a View.
[ { "change_type": "MODIFY", "old_path": "pkg/bufferv2/view.go", "new_path": "pkg/bufferv2/view.go", "diff": "@@ -161,6 +161,16 @@ func (v *View) AsSlice() []byte {\nreturn v.chunk.data[v.read:v.write]\n}\n+// ToSlice returns an owned copy of the data in this view.\n+func (v *View) ToSlice() []byte {\n+ if v.Size() == 0 {\n+ return nil\n+ }\n+ s := make([]byte, v.Size())\n+ copy(s, v.AsSlice())\n+ return s\n+}\n+\n// AvailableSize returns the number of bytes available for writing.\nfunc (v *View) AvailableSize() int {\nif v == nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Add a method that returns an owned copy of the data in a View. PiperOrigin-RevId: 463703416
259,975
29.07.2022 13:33:35
25,200
8a7a35e9d6257acec554304d4fe3d4abc86dbde4
[gke-perf] Add "latest" tag to gcr.io images.
[ { "change_type": "MODIFY", "old_path": "tools/images.mk", "new_path": "tools/images.mk", "diff": "@@ -135,6 +135,7 @@ rebuild = \\\ndocker build $(DOCKER_PLATFORM_ARGS) \\\n-f \"$$T/$(call dockerfile,$(1))\" \\\n-t \"$(call remote_image,$(1)):$(call tag,$(1))\" \\\n+ -t \"$(call remote_image,$(1))\":latest \\\n$$T >&2 && \\\nrm -rf $$T) && \\\n$(call local_tag,$(1)) && \\\n@@ -152,7 +153,8 @@ load-%: register-cross ## Pull or build an image locally.\n# already exists) or building manually. Note that this generic rule will match\n# the fully-expanded remote image tag.\npush-%: load-% ## Push a given image.\n- @docker push $(call remote_image,$*):$(call tag,$*) >&2\n+ @docker image push $(call remote_image,$*):$(call tag,$*) >&2\n+ @docker image push $(call remote_image,$*):latest >&2\n# register-cross registers the necessary qemu binaries for cross-compilation.\n# This may be used by any target that may execute containers that are not the\n" } ]
Go
Apache License 2.0
google/gvisor
[gke-perf] Add "latest" tag to gcr.io images. PiperOrigin-RevId: 464147312
259,907
31.07.2022 17:59:28
25,200
d91c459a7860b85e82dacb18cde6ba50bfe6f209
Always initialize a/m/c times and nlink in VFS2 gofer client. When the server does not provide these values, they should be initialized to something sensible. This is consistent with VFS1.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/BUILD", "new_path": "pkg/sentry/fsimpl/gofer/BUILD", "diff": "@@ -97,6 +97,7 @@ go_test(\ndeps = [\n\"//pkg/p9\",\n\"//pkg/sentry/contexttest\",\n+ \"//pkg/sentry/kernel/time\",\n\"//pkg/sentry/pgalloc\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/gofer.go", "new_path": "pkg/sentry/fsimpl/gofer/gofer.go", "diff": "@@ -1051,18 +1051,31 @@ func (fs *filesystem) newDentry(ctx context.Context, file p9file, qid p9.QID, ma\n}\nif mask.ATime {\nd.atime = atomicbitops.FromInt64(dentryTimestampFromP9(attr.ATimeSeconds, attr.ATimeNanoSeconds))\n+ } else {\n+ d.atime = atomicbitops.FromInt64(fs.clock.Now().Nanoseconds())\n}\nif mask.MTime {\nd.mtime = atomicbitops.FromInt64(dentryTimestampFromP9(attr.MTimeSeconds, attr.MTimeNanoSeconds))\n+ } else {\n+ d.mtime = atomicbitops.FromInt64(fs.clock.Now().Nanoseconds())\n}\nif mask.CTime {\nd.ctime = atomicbitops.FromInt64(dentryTimestampFromP9(attr.CTimeSeconds, attr.CTimeNanoSeconds))\n+ } else {\n+ // Approximate ctime with mtime if ctime isn't available.\n+ d.ctime = atomicbitops.FromInt64(d.mtime.Load())\n}\nif mask.BTime {\nd.btime = atomicbitops.FromInt64(dentryTimestampFromP9(attr.BTimeSeconds, attr.BTimeNanoSeconds))\n}\nif mask.NLink {\nd.nlink = atomicbitops.FromUint32(uint32(attr.NLink))\n+ } else {\n+ if attr.Mode.FileType() == p9.ModeDirectory {\n+ d.nlink = atomicbitops.FromUint32(2)\n+ } else {\n+ d.nlink = atomicbitops.FromUint32(1)\n+ }\n}\nd.vfsd.Init(d)\nrefsvfs2.Register(d)\n@@ -1112,18 +1125,31 @@ func (fs *filesystem) newDentryLisa(ctx context.Context, ino *lisafs.Inode) (*de\n}\nif ino.Stat.Mask&linux.STATX_ATIME != 0 {\nd.atime = atomicbitops.FromInt64(dentryTimestampFromLisa(ino.Stat.Atime))\n+ } else {\n+ d.atime = atomicbitops.FromInt64(fs.clock.Now().Nanoseconds())\n}\nif ino.Stat.Mask&linux.STATX_MTIME != 0 {\nd.mtime = atomicbitops.FromInt64(dentryTimestampFromLisa(ino.Stat.Mtime))\n+ } else {\n+ d.mtime = atomicbitops.FromInt64(fs.clock.Now().Nanoseconds())\n}\nif ino.Stat.Mask&linux.STATX_CTIME != 0 {\nd.ctime = atomicbitops.FromInt64(dentryTimestampFromLisa(ino.Stat.Ctime))\n+ } else {\n+ // Approximate ctime with mtime if ctime isn't available.\n+ d.ctime = atomicbitops.FromInt64(d.mtime.Load())\n}\nif ino.Stat.Mask&linux.STATX_BTIME != 0 {\nd.btime = atomicbitops.FromInt64(dentryTimestampFromLisa(ino.Stat.Btime))\n}\nif ino.Stat.Mask&linux.STATX_NLINK != 0 {\nd.nlink = atomicbitops.FromUint32(ino.Stat.Nlink)\n+ } else {\n+ if ino.Stat.Mode&linux.FileTypeMask == linux.ModeDirectory {\n+ d.nlink = atomicbitops.FromUint32(2)\n+ } else {\n+ d.nlink = atomicbitops.FromUint32(1)\n+ }\n}\nd.vfsd.Init(d)\nrefsvfs2.Register(d)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/gofer_test.go", "new_path": "pkg/sentry/fsimpl/gofer/gofer_test.go", "diff": "@@ -19,6 +19,7 @@ import (\n\"gvisor.dev/gvisor/pkg/p9\"\n\"gvisor.dev/gvisor/pkg/sentry/contexttest\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n\"gvisor.dev/gvisor/pkg/sentry/pgalloc\"\n)\n@@ -29,6 +30,7 @@ func TestDestroyIdempotent(t *testing.T) {\nsyncableDentries: make(map[*dentry]struct{}),\ninoByQIDPath: make(map[uint64]uint64),\ninoByKey: make(map[inoKey]uint64),\n+ clock: time.RealtimeClockFromContext(ctx),\n// Test relies on no dentry being held in the cache.\ndentryCache: &dentryCache{maxCachedDentries: 0},\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Always initialize a/m/c times and nlink in VFS2 gofer client. When the server does not provide these values, they should be initialized to something sensible. This is consistent with VFS1. PiperOrigin-RevId: 464433106
260,009
01.08.2022 09:52:36
25,200
1d3b90268d374c25e9f7f5b6b63c1024060e42f8
Replace "Register" nomenclature for timer metrics init functions. In the context set by Uint64Metrics, the "Register..." functions are used for custom metric types defined outside of the metric pkg, where as the "New..." and "MustCreateNew..." are used for those types belonging to the metric pkg.
[ { "change_type": "MODIFY", "old_path": "pkg/metric/metric.go", "new_path": "pkg/metric/metric.go", "diff": "@@ -395,8 +395,8 @@ func NewUint64Metric(name string, sync bool, units pb.MetricMetadata_Units, desc\nreturn &m, RegisterCustomUint64Metric(name, true /* cumulative */, sync, units, description, m.Value, fields...)\n}\n-// MustCreateNewUint64Metric calls NewUint64Metric and panics if it returns an\n-// error.\n+// MustCreateNewUint64Metric calls RegisterUint64Metric and panics if it returns\n+// an error.\nfunc MustCreateNewUint64Metric(name string, sync bool, description string, fields ...Field) *Uint64Metric {\nm, err := NewUint64Metric(name, sync, pb.MetricMetadata_UNITS_NONE, description, fields...)\nif err != nil {\n@@ -670,9 +670,9 @@ func NewDistributionMetric(name string, sync bool, bucketer Bucketer, unit pb.Me\nreturn allMetrics.distributionMetrics[name], nil\n}\n-// MustRegisterDistributionMetric creates and registers a distribution metric.\n+// MustCreateNewDistributionMetric creates and registers a distribution metric.\n// If an error occurs, it panics.\n-func MustRegisterDistributionMetric(name string, sync bool, bucketer Bucketer, unit pb.MetricMetadata_Units, description string, fields ...Field) *DistributionMetric {\n+func MustCreateNewDistributionMetric(name string, sync bool, bucketer Bucketer, unit pb.MetricMetadata_Units, description string, fields ...Field) *DistributionMetric {\ndistrib, err := NewDistributionMetric(name, sync, bucketer, unit, description, fields...)\nif err != nil {\npanic(err)\n@@ -738,9 +738,9 @@ func NewTimerMetric(name string, nanoBucketer Bucketer, description string, fiel\n}, nil\n}\n-// MustRegisterTimerMetric creates and registers a timer metric.\n+// MustCreateNewTimerMetric creates and registers a timer metric.\n// If an error occurs, it panics.\n-func MustRegisterTimerMetric(name string, nanoBucketer Bucketer, description string, fields ...Field) *TimerMetric {\n+func MustCreateNewTimerMetric(name string, nanoBucketer Bucketer, description string, fields ...Field) *TimerMetric {\ntimer, err := NewTimerMetric(name, nanoBucketer, description, fields...)\nif err != nil {\npanic(err)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine.go", "new_path": "pkg/sentry/platform/kvm/machine.go", "diff": "@@ -131,7 +131,7 @@ var (\nmetric.NewField(\"acquisition_type\", []string{\"fast_reused\", \"reused\", \"unused\", \"stolen\"}))\n// asInvalidateDuration are durations of calling addressSpace.invalidate().\n- asInvalidateDuration = metric.MustRegisterTimerMetric(\"/kvm/address_space_invalidate\",\n+ asInvalidateDuration = metric.MustCreateNewTimerMetric(\"/kvm/address_space_invalidate\",\nmetric.NewExponentialBucketer(15, uint64(time.Nanosecond*100), 1, 2),\n\"Duration of calling addressSpace.invalidate().\")\n)\n" } ]
Go
Apache License 2.0
google/gvisor
Replace "Register" nomenclature for timer metrics init functions. In the context set by Uint64Metrics, the "Register..." functions are used for custom metric types defined outside of the metric pkg, where as the "New..." and "MustCreateNew..." are used for those types belonging to the metric pkg. PiperOrigin-RevId: 464558365
259,891
01.08.2022 10:09:28
25,200
03b682624382fb7a8913101686f5751b3180becb
xdp: tooling and dependencies Setup gVisor so that an AF_XDP dispatcher can be implemented. Specifically: xdp_loader: a binary for testing XDP programs Two basic XDP programs Update the cilium/ebpf dep Genrule for building BPF programs Install clang on buildkite to support building BPF programs
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -15,11 +15,11 @@ http_file(\n# Bazel/starlark utilities.\nhttp_archive(\nname = \"bazel_skylib\",\n+ sha256 = \"f7be3474d42aae265405a592bb7da8e171919d74c16f082a5457840f06054728\",\nurls = [\n\"https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz\",\n\"https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz\",\n],\n- sha256 = \"f7be3474d42aae265405a592bb7da8e171919d74c16f082a5457840f06054728\",\n)\nload(\"@bazel_skylib//:workspace.bzl\", \"bazel_skylib_workspace\")\n@@ -1484,8 +1484,8 @@ go_repository(\ngo_repository(\nname = \"com_github_cilium_ebpf\",\nimportpath = \"github.com/cilium/ebpf\",\n- sum = \"h1:QlHdikaxALkqWasW8hAC1mfR0jdmvbfaBdBPFmRSglA=\",\n- version = \"v0.4.0\",\n+ sum = \"h1:64sn2K3UKw8NbP/blsixRpF3nXuyhz/VjRlRzvlBRu4=\",\n+ version = \"v0.9.1\",\n)\ngo_repository(\n" }, { "change_type": "MODIFY", "old_path": "tools/bazeldefs/defs.bzl", "new_path": "tools/bazeldefs/defs.bzl", "diff": "@@ -72,3 +72,24 @@ def default_net_util():\ndef coreutil():\nreturn [] # Nothing needed.\n+\n+def bpf_program(name, src, bpf_object, visibility, hdrs):\n+ \"\"\"Generates BPF object files from .c source code.\n+\n+ Args:\n+ name: target name for BPF program.\n+ src: BPF program souce code in C.\n+ bpf_object: name of generated bpf object code.\n+ visibility: target visibility.\n+ hdrs: header files, but currently unsupported.\n+ \"\"\"\n+ if hdrs != []:\n+ fail(\"hdrs attribute is unsupported\")\n+\n+ native.genrule(\n+ name = name,\n+ srcs = [src],\n+ visibility = visibility,\n+ outs = [bpf_object],\n+ cmd = \"clang -O2 -Wall -Werror -target bpf -c $< -o $@\",\n+ )\n" }, { "change_type": "MODIFY", "old_path": "tools/defs.bzl", "new_path": "tools/defs.bzl", "diff": "@@ -8,7 +8,7 @@ change for Google-internal and bazel-compatible rules.\nload(\"//tools/go_stateify:defs.bzl\", \"go_stateify\")\nload(\"//tools/go_marshal:defs.bzl\", \"go_marshal\", \"marshal_deps\", \"marshal_test_deps\")\nload(\"//tools/nogo:defs.bzl\", \"nogo_test\")\n-load(\"//tools/bazeldefs:defs.bzl\", _BuildSettingInfo = \"BuildSettingInfo\", _amd64_config = \"amd64_config\", _arch_config = \"arch_config\", _arm64_config = \"arm64_config\", _bool_flag = \"bool_flag\", _build_test = \"build_test\", _bzl_library = \"bzl_library\", _coreutil = \"coreutil\", _default_net_util = \"default_net_util\", _more_shards = \"more_shards\", _most_shards = \"most_shards\", _proto_library = \"proto_library\", _select_arch = \"select_arch\", _select_system = \"select_system\", _short_path = \"short_path\", _transition_allowlist = \"transition_allowlist\", _version = \"version\")\n+load(\"//tools/bazeldefs:defs.bzl\", _BuildSettingInfo = \"BuildSettingInfo\", _amd64_config = \"amd64_config\", _arch_config = \"arch_config\", _arm64_config = \"arm64_config\", _bool_flag = \"bool_flag\", _bpf_program = \"bpf_program\", _build_test = \"build_test\", _bzl_library = \"bzl_library\", _coreutil = \"coreutil\", _default_net_util = \"default_net_util\", _more_shards = \"more_shards\", _most_shards = \"most_shards\", _proto_library = \"proto_library\", _select_arch = \"select_arch\", _select_system = \"select_system\", _short_path = \"short_path\", _transition_allowlist = \"transition_allowlist\", _version = \"version\")\nload(\"//tools/bazeldefs:cc.bzl\", _cc_binary = \"cc_binary\", _cc_flags_supplier = \"cc_flags_supplier\", _cc_grpc_library = \"cc_grpc_library\", _cc_library = \"cc_library\", _cc_proto_library = \"cc_proto_library\", _cc_test = \"cc_test\", _cc_toolchain = \"cc_toolchain\", _gbenchmark = \"gbenchmark\", _gbenchmark_internal = \"gbenchmark_internal\", _grpcpp = \"grpcpp\", _gtest = \"gtest\", _vdso_linker_option = \"vdso_linker_option\")\nload(\"//tools/bazeldefs:go.bzl\", _gazelle = \"gazelle\", _go_binary = \"go_binary\", _go_embed_data = \"go_embed_data\", _go_grpc_and_proto_libraries = \"go_grpc_and_proto_libraries\", _go_library = \"go_library\", _go_path = \"go_path\", _go_proto_library = \"go_proto_library\", _go_rule = \"go_rule\", _go_test = \"go_test\", _gotsan_flag_values = \"gotsan_flag_values\", _gotsan_values = \"gotsan_values\", _select_goarch = \"select_goarch\", _select_goos = \"select_goos\")\nload(\"//tools/bazeldefs:pkg.bzl\", _pkg_deb = \"pkg_deb\", _pkg_tar = \"pkg_tar\")\n@@ -52,6 +52,9 @@ go_proto_library = _go_proto_library\ngotsan_values = _gotsan_values\ngotsan_flag_values = _gotsan_flag_values\n+# BPF rules.\n+bpf_program = _bpf_program\n+\n# Packaging rules.\npkg_deb = _pkg_deb\npkg_tar = _pkg_tar\n@@ -117,6 +120,7 @@ def go_binary(name, nogo = True, pure = False, static = False, x_defs = None, **\nname = name + \"_nogo_library\",\nsrcs = kwargs.get(\"srcs\", []),\ndeps = kwargs.get(\"deps\", []),\n+ embedsrcs = kwargs.get(\"embedsrcs\", []),\ntestonly = 1,\n)\nnogo_test(\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/xdp/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"go_binary\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_binary(\n+ name = \"xdp_loader\",\n+ srcs = [\n+ \"main.go\",\n+ ],\n+ embedsrcs = [\n+ \"//tools/xdp/bpf:drop_ebpf.o\", # keep\n+ \"//tools/xdp/bpf:pass_ebpf.o\", # keep\n+ ],\n+ visibility = [\"//:sandbox\"],\n+ deps = [\n+ \"@com_github_cilium_ebpf//:go_default_library\",\n+ \"@com_github_cilium_ebpf//link:go_default_library\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/xdp/bpf/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"bpf_program\")\n+\n+package(licenses = [\"notice\"])\n+\n+bpf_program(\n+ name = \"pass_ebpf\",\n+ src = \"pass.ebpf.c\",\n+ hdrs = [],\n+ bpf_object = \"pass_ebpf.o\",\n+ visibility = [\"//:sandbox\"],\n+)\n+\n+bpf_program(\n+ name = \"drop_ebpf\",\n+ src = \"drop.ebpf.c\",\n+ hdrs = [],\n+ bpf_object = \"drop_ebpf.o\",\n+ visibility = [\"//:sandbox\"],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/xdp/bpf/drop.ebpf.c", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <linux/bpf.h>\n+\n+#define section(secname) __attribute__((section(secname), used))\n+\n+char __license[] section(\"license\") = \"Apache-2.0\";\n+\n+// You probably shouldn't change the section or function name. Each is used by\n+// BPF tooling, and so changes can cause runtime failures.\n+section(\"xdp\") int xdp_prog(struct xdp_md *ctx) { return XDP_DROP; }\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/xdp/bpf/pass.ebpf.c", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <linux/bpf.h>\n+\n+#define section(secname) __attribute__((section(secname), used))\n+\n+char __license[] section(\"license\") = \"Apache-2.0\";\n+\n+// You probably shouldn't change the section or function name. Each is used by\n+// BPF tooling, and so changes can cause runtime failures.\n+section(\"xdp\") int xdp_prog(struct xdp_md *ctx) { return XDP_PASS; }\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/xdp/main.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// The xdp_loader tool is used to load compiled XDP object files into the XDP\n+// hook of a net device. It is intended primarily for testing.\n+package main\n+\n+import (\n+ \"bytes\"\n+ _ \"embed\"\n+ \"flag\"\n+ \"log\"\n+ \"net\"\n+\n+ \"github.com/cilium/ebpf\"\n+ \"github.com/cilium/ebpf/link\"\n+ \"golang.org/x/sys/unix\"\n+)\n+\n+var (\n+ device = flag.String(\"device\", \"\", \"which device to attach to\")\n+ program = flag.String(\"program\", \"\", \"which program to install: one of [pass, drop]\")\n+)\n+\n+// Builtin programs selectable by users.\n+var (\n+ //go:embed bpf/pass_ebpf.o\n+ pass []byte\n+\n+ //go:embed bpf/drop_ebpf.o\n+ drop []byte\n+)\n+\n+var programs = map[string][]byte{\n+ \"pass\": pass,\n+ \"drop\": drop,\n+}\n+\n+func main() {\n+ // Sanity check.\n+ if len(pass) == 0 {\n+ panic(\"the pass program failed to embed\")\n+ }\n+ if len(drop) == 0 {\n+ panic(\"the drop program failed to embed\")\n+ }\n+\n+ flag.Parse()\n+\n+ // Get a net device.\n+ if *device == \"\" {\n+ log.Fatalf(\"must specify -device\")\n+ }\n+ iface, err := net.InterfaceByName(*device)\n+ if err != nil {\n+ log.Fatalf(\"unknown device %q: %v\", *device, err)\n+ }\n+\n+ // Choose a program.\n+ if *program == \"\" {\n+ log.Fatalf(\"must specify -program\")\n+ }\n+ progData, ok := programs[*program]\n+ if !ok {\n+ log.Fatalf(\"unknown program %q\", *program)\n+ }\n+\n+ // Load into the kernel. Note that this is usually done using bpf2go,\n+ // but since we haven't set up that tool we do everything manually.\n+ spec, err := ebpf.LoadCollectionSpecFromReader(bytes.NewReader(progData))\n+ if err != nil {\n+ log.Fatalf(\"failed to load spec: %v\", err)\n+ }\n+\n+ // We need to pass a struct with a field of a specific type and tag.\n+ var objects struct {\n+ Program *ebpf.Program `ebpf:\"xdp_prog\"`\n+ }\n+ if err := spec.LoadAndAssign(&objects, nil); err != nil {\n+ log.Fatalf(\"failed to load program: %v\", err)\n+ }\n+ defer func() {\n+ if err := objects.Program.Close(); err != nil {\n+ log.Printf(\"failed to close program: %v\", err)\n+ }\n+ }()\n+\n+ // Attach the program to the XDP hook on the device. Fallback from best\n+ // to worst mode.\n+ modes := []struct {\n+ name string\n+ flag link.XDPAttachFlags\n+ }{\n+ {name: \"offload\", flag: link.XDPOffloadMode},\n+ {name: \"driver\", flag: link.XDPDriverMode},\n+ {name: \"generic\", flag: link.XDPGenericMode},\n+ }\n+ var attached link.Link\n+ for _, mode := range modes {\n+ attached, err = link.AttachXDP(link.XDPOptions{\n+ Program: objects.Program,\n+ Interface: iface.Index,\n+ Flags: mode.flag,\n+ })\n+ if err == nil {\n+ log.Printf(\"attached with mode %q\", mode.name)\n+ break\n+ }\n+ log.Printf(\"failed to attach with mode %q: %v\", mode.name, err)\n+ }\n+ if attached == nil {\n+ log.Fatalf(\"failed to attach program\")\n+ }\n+ defer attached.Close()\n+\n+ log.Printf(\"Successfully attached! Press CTRL-C to quit and remove the program from the device.\")\n+ for {\n+ unix.Pause()\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
xdp: tooling and dependencies Setup gVisor so that an AF_XDP dispatcher can be implemented. Specifically: - xdp_loader: a binary for testing XDP programs - Two basic XDP programs - Update the cilium/ebpf dep - Genrule for building BPF programs - Install clang on buildkite to support building BPF programs PiperOrigin-RevId: 464562411
259,975
01.08.2022 12:01:41
25,200
991841786a92a40a0514a1236a6c4362a1850271
[sst] Cleanup TODOs for SecurityMessages
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_exec.go", "new_path": "pkg/sentry/kernel/task_exec.go", "diff": "@@ -329,8 +329,6 @@ func getExecveSeccheckInfo(t *Task, argv, env []string, executable fsbridge.File\n}\n}\n}\n- // TODO(b/202293325): Decide if we actually want to offer binary\n- // SHA256, which is very expensive.\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
[sst] Cleanup TODOs for SecurityMessages PiperOrigin-RevId: 464589591
259,992
02.08.2022 16:04:05
25,200
49a3911d53d37d411d1261a589d302510c4ce016
Reorder Quick Start to put easier stuff on the top
[ { "change_type": "MODIFY", "old_path": "g3doc/user_guide/quick_start/BUILD", "new_path": "g3doc/user_guide/quick_start/BUILD", "diff": "@@ -15,19 +15,19 @@ doc(\n)\ndoc(\n- name = \"oci\",\n- src = \"oci.md\",\n+ name = \"kubernetes\",\n+ src = \"kubernetes.md\",\ncategory = \"User Guide\",\n- permalink = \"/docs/user_guide/quick_start/oci/\",\n+ permalink = \"/docs/user_guide/quick_start/kubernetes/\",\nsubcategory = \"Quick Start\",\nweight = \"12\",\n)\ndoc(\n- name = \"kubernetes\",\n- src = \"kubernetes.md\",\n+ name = \"oci\",\n+ src = \"oci.md\",\ncategory = \"User Guide\",\n- permalink = \"/docs/user_guide/quick_start/kubernetes/\",\n+ permalink = \"/docs/user_guide/quick_start/oci/\",\nsubcategory = \"Quick Start\",\nweight = \"13\",\n)\n" }, { "change_type": "MODIFY", "old_path": "g3doc/user_guide/quick_start/kubernetes.md", "new_path": "g3doc/user_guide/quick_start/kubernetes.md", "diff": "gVisor can be used to run Kubernetes pods and has several integration points\nwith Kubernetes.\n+## Using GKE Sandbox\n+\n+[GKE Sandbox][gke-sandbox] is available in [Google Kubernetes Engine][gke]. You\n+just need to deploy a node pool with gVisor enabled in your cluster, and it will\n+run pods annotated with `runtimeClassName: gvisor` inside a gVisor sandbox for\n+you. [Here][wordpress-quick] is a quick example showing how to deploy a\n+WordPress site. You can view the full documentation [here][gke-sandbox-docs].\n+\n## Using Minikube\ngVisor can run sandboxed containers in a Kubernetes cluster with Minikube. After\n@@ -16,14 +24,6 @@ You can also setup Kubernetes nodes to run pods in gVisor using\n[containerd][containerd] and the gVisor containerd shim. You can find\ninstructions in the [Containerd Quick Start][gvisor-containerd].\n-## Using GKE Sandbox\n-\n-[GKE Sandbox][gke-sandbox] is available in [Google Kubernetes Engine][gke]. You\n-just need to deploy a node pool with gVisor enabled in your cluster, and it will\n-run pods annotated with `runtimeClassName: gvisor` inside a gVisor sandbox for\n-you. [Here][wordpress-quick] is a quick example showing how to deploy a\n-WordPress site. You can view the full documentation [here][gke-sandbox-docs].\n-\n[containerd]: https://containerd.io/\n[minikube]: https://github.com/kubernetes/minikube/blob/master/deploy/addons/gvisor/README.md\n[gke]: https://cloud.google.com/kubernetes-engine/\n" } ]
Go
Apache License 2.0
google/gvisor
Reorder Quick Start to put easier stuff on the top PiperOrigin-RevId: 464909911
259,992
02.08.2022 16:35:38
25,200
87f4e4a18810b6bf478e171801132537de7aeda5
Update Wordpress Kubernetes instructions They were still referencing the gcloud beta commands.
[ { "change_type": "MODIFY", "old_path": "g3doc/user_guide/tutorials/add-node-pool.png", "new_path": "g3doc/user_guide/tutorials/add-node-pool.png", "diff": "Binary files a/g3doc/user_guide/tutorials/add-node-pool.png and b/g3doc/user_guide/tutorials/add-node-pool.png differ\n" }, { "change_type": "MODIFY", "old_path": "g3doc/user_guide/tutorials/kubernetes.md", "new_path": "g3doc/user_guide/tutorials/kubernetes.md", "diff": "@@ -16,8 +16,8 @@ Take the following steps to enable the Kubernetes Engine API:\nCreate a node pool inside your cluster with option `--sandbox type=gvisor` added\nto the command, like below:\n-```bash\n-gcloud beta container node-pools create sandbox-pool --cluster=${CLUSTER_NAME} --image-type=cos_containerd --sandbox type=gvisor\n+```shell\n+gcloud container node-pools create gvisor --cluster=${CLUSTER_NAME?} --sandbox type=gvisor --machine-type=e2-standard-2\n```\nIf you prefer to use the console, select your cluster and select the **ADD NODE\n@@ -25,8 +25,8 @@ POOL** button:\n![+ ADD NODE POOL](node-pool-button.png)\n-Then select the **Image type** with **Containerd** and select **Enable sandbox\n-with gVisor** option. Select other options as you like:\n+Then click on the **Security** tab on the left and select **Enable sandbox with\n+gVisor** option. Select other options as you like:\n![+ NODE POOL](add-node-pool.png)\n@@ -35,8 +35,10 @@ with gVisor** option. Select other options as you like:\nThe gvisor RuntimeClass is instantiated during node creation. You can check for\nthe existence of the gvisor RuntimeClass using the following command:\n-```bash\n-kubectl get runtimeclasses\n+```shell\n+$ kubectl get runtimeclass/gvisor\n+NAME HANDLER AGE\n+gvisor gvisor 1h\n```\n### Wordpress deployment\n@@ -49,7 +51,7 @@ they use secret store to share MySQL password between them.\nFirst, let's download the deployment configuration files to add the runtime\nclass annotation to them:\n-```bash\n+```shell\ncurl -LO https://k8s.io/examples/application/wordpress/wordpress-deployment.yaml\ncurl -LO https://k8s.io/examples/application/wordpress/mysql-deployment.yaml\n```\n@@ -207,7 +209,7 @@ Deployment has is changed.\nYou are now ready to deploy the entire application. Just create a secret to\nstore MySQL's password and *apply* both deployments:\n-```bash\n+```shell\nkubectl create secret generic mysql-pass --from-literal=password=${YOUR_SECRET_PASSWORD_HERE?}\nkubectl apply -f mysql-deployment.yaml\nkubectl apply -f wordpress-deployment.yaml\n@@ -216,12 +218,14 @@ kubectl apply -f wordpress-deployment.yaml\nWait for the deployments to be ready and an external IP to be assigned to the\nWordpress service:\n-```bash\n-watch kubectl get service wordpress\n+```shell\n+$ watch kubectl get service wordpress\n+NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE\n+wordpress LoadBalancer 10.120.16.63 35.203.179.216 80:31025/TCP 1m\n```\n-Now, copy the service `EXTERNAL-IP` from above to your favorite browser to view\n-and configure your new WordPress site.\n+Now, copy the service's `EXTERNAL-IP` from above to your favorite browser to\n+view and configure your new WordPress site.\nCongratulations! You have just deployed a WordPress site using GKE Sandbox.\n" } ]
Go
Apache License 2.0
google/gvisor
Update Wordpress Kubernetes instructions They were still referencing the gcloud beta commands. PiperOrigin-RevId: 464916524
259,881
03.08.2022 08:28:37
25,200
974792ae18cf19f555a35d3bf7b23a8ed9e9385c
Bump negative build tag constraints to go1.21
[ { "change_type": "MODIFY", "old_path": "pkg/gohacks/gohacks_unsafe.go", "new_path": "pkg/gohacks/gohacks_unsafe.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-//go:build go1.13 && !go1.20\n-// +build go1.13,!go1.20\n+//go:build go1.13 && !go1.21\n+// +build go1.13,!go1.21\n// //go:linkname directives type-checked by checklinkname. Any other\n// non-linkname assumptions outside the Go 1 compatibility guarantee should\n" }, { "change_type": "MODIFY", "old_path": "pkg/goid/goid.go", "new_path": "pkg/goid/goid.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-//go:build go1.12 && !go1.20\n-// +build go1.12,!go1.20\n+//go:build go1.12 && !go1.21\n+// +build go1.12,!go1.21\n// Check type signatures when updating Go version.\n" }, { "change_type": "MODIFY", "old_path": "pkg/procid/procid_amd64.s", "new_path": "pkg/procid/procid_amd64.s", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-//go:build amd64 && go1.8 && !go1.20 && go1.1\n-// +build amd64,go1.8,!go1.20,go1.1\n+//go:build amd64 && go1.8 && !go1.21 && go1.1\n+// +build amd64,go1.8,!go1.21,go1.1\n// //go:linkname directives type-checked by checklinkname. Any other\n// non-linkname assumptions outside the Go 1 compatibility guarantee should\n" }, { "change_type": "MODIFY", "old_path": "pkg/procid/procid_arm64.s", "new_path": "pkg/procid/procid_arm64.s", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-//go:build arm64 && go1.8 && !go1.20 && go1.1\n-// +build arm64,go1.8,!go1.20,go1.1\n+//go:build arm64 && go1.8 && !go1.21 && go1.1\n+// +build arm64,go1.8,!go1.21,go1.1\n// //go:linkname directives type-checked by checklinkname. Any other\n// non-linkname assumptions outside the Go 1 compatibility guarantee should\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/mutex_unsafe.go", "new_path": "pkg/sync/mutex_unsafe.go", "diff": "// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n-//go:build go1.13 && !go1.20\n-// +build go1.13,!go1.20\n+//go:build go1.13 && !go1.21\n+// +build go1.13,!go1.21\n// When updating the build constraint (above), check that syncMutex matches the\n// standard library sync.Mutex definition.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/runtime_amd64.go", "new_path": "pkg/sync/runtime_amd64.go", "diff": "// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n-//go:build amd64 && go1.8 && !go1.20 && !goexperiment.staticlockranking\n-// +build amd64,go1.8,!go1.20,!goexperiment.staticlockranking\n+//go:build amd64 && go1.8 && !go1.21 && !goexperiment.staticlockranking\n+// +build amd64,go1.8,!go1.21,!goexperiment.staticlockranking\npackage sync\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/runtime_amd64.s", "new_path": "pkg/sync/runtime_amd64.s", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-//go:build amd64 && go1.14 && !go1.20 && !goexperiment.staticlockranking\n-// +build amd64,go1.14,!go1.20,!goexperiment.staticlockranking\n+//go:build amd64 && go1.14 && !go1.21 && !goexperiment.staticlockranking\n+// +build amd64,go1.14,!go1.21,!goexperiment.staticlockranking\n#include \"textflag.h\"\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/runtime_unsafe.go", "new_path": "pkg/sync/runtime_unsafe.go", "diff": "// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n-//go:build go1.13 && !go1.20\n-// +build go1.13,!go1.20\n+//go:build go1.13 && !go1.21\n+// +build go1.13,!go1.21\n// //go:linkname directives type-checked by checklinkname. Any other\n// non-linkname assumptions outside the Go 1 compatibility guarantee should\n" } ]
Go
Apache License 2.0
google/gvisor
Bump negative build tag constraints to go1.21 PiperOrigin-RevId: 465062413
259,909
03.08.2022 12:22:02
25,200
1c220bf2a4a0a6c8cdaf3c092b1a3d22391b6e42
Fix refsvfs2 bug that counted uninitialized leak checking as enabled.
[ { "change_type": "MODIFY", "old_path": "pkg/refsvfs2/refs_map.go", "new_path": "pkg/refsvfs2/refs_map.go", "diff": "@@ -50,7 +50,8 @@ func init() {\n// LeakCheckEnabled returns whether leak checking is enabled. The following\n// functions should only be called if it returns true.\nfunc LeakCheckEnabled() bool {\n- return refs_vfs1.GetLeakMode() != refs_vfs1.NoLeakChecking\n+ mode := refs_vfs1.GetLeakMode()\n+ return mode != refs_vfs1.NoLeakChecking && mode != refs_vfs1.UninitializedLeakChecking\n}\n// leakCheckPanicEnabled returns whether DoLeakCheck() should panic when leaks\n" } ]
Go
Apache License 2.0
google/gvisor
Fix refsvfs2 bug that counted uninitialized leak checking as enabled. PiperOrigin-RevId: 465118656
259,992
03.08.2022 14:30:26
25,200
dc4cd669fcf90e758927d5ebbc79d3fb1547c597
Add sinks to `runsc trace metadata` output Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/seccheck/config.go", "new_path": "pkg/sentry/seccheck/config.go", "diff": "@@ -225,7 +225,7 @@ func setFields(names []string, fields []FieldDesc) (FieldMask, error) {\n}\nfunc findSinkDesc(name string) (SinkDesc, error) {\n- if desc, ok := sinks[name]; ok {\n+ if desc, ok := Sinks[name]; ok {\nreturn desc, nil\n}\nreturn SinkDesc{}, fmt.Errorf(\"sink %q not found\", name)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/seccheck/metadata.go", "new_path": "pkg/sentry/seccheck/metadata.go", "diff": "@@ -61,11 +61,13 @@ const (\nFieldSentryExecveBinaryInfo Field = iota\n)\n-// Points is a map with all the Points registered in the system.\n+// Points is a map with all the trace points registered in the system.\nvar Points = map[string]PointDesc{}\n-var sinks = map[string]SinkDesc{}\n-// defaultContextFields are the fields present in most Points.\n+// Sinks is a map with all the sinks registered in the system.\n+var Sinks = map[string]SinkDesc{}\n+\n+// defaultContextFields are the fields present in most trace points.\nvar defaultContextFields = []FieldDesc{\n{\nID: FieldCtxtTime,\n@@ -122,10 +124,10 @@ type SinkDesc struct {\n// RegisterSink registers a new sink to make it discoverable.\nfunc RegisterSink(sink SinkDesc) {\n- if _, ok := sinks[sink.Name]; ok {\n+ if _, ok := Sinks[sink.Name]; ok {\npanic(fmt.Sprintf(\"Sink %q already registered\", sink.Name))\n}\n- sinks[sink.Name] = sink\n+ Sinks[sink.Name] = sink\n}\n// PointDesc describes a Point that is available to be configured.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/seccheck/metadata_test.go", "new_path": "pkg/sentry/seccheck/metadata_test.go", "diff": "@@ -21,7 +21,7 @@ import (\nfunc TestSinkRegistration(t *testing.T) {\nsink := SinkDesc{Name: \"test\"}\nRegisterSink(sink)\n- if _, ok := sinks[\"test\"]; !ok {\n+ if _, ok := Sinks[\"test\"]; !ok {\nt.Errorf(\"sink registration failed\")\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/trace/metadata.go", "new_path": "runsc/cmd/trace/metadata.go", "diff": "@@ -64,6 +64,11 @@ func (l *metadata) Execute(context.Context, *flag.FlagSet, ...interface{}) subco\nctxFields := fieldNames(pt.ContextFields)\nfmt.Printf(\"Name: %s, optional fields: [%s], context fields: [%s]\\n\", pt.Name, strings.Join(optFields, \"|\"), strings.Join(ctxFields, \"|\"))\n}\n+ fmt.Printf(\"\\nSINKS (%d)\\n\", len(seccheck.Sinks))\n+ for _, sink := range seccheck.Sinks {\n+ fmt.Printf(\"Name: %s\\n\", sink.Name)\n+ }\n+\nreturn subcommands.ExitSuccess\n}\n" }, { "change_type": "MODIFY", "old_path": "test/trace/config/config.go", "new_path": "test/trace/config/config.go", "diff": "@@ -61,14 +61,24 @@ func (b *Builder) LoadAllPoints(runscPath string) error {\n// The command above produces an output like the following:\n// POINTS (907)\n// Name: container/start, optional fields: [], context fields: [time|thread_id]\n+ //\n+ // SINKS (2)\n+ // Name: remote\nscanner := bufio.NewScanner(bytes.NewReader(out))\nif !scanner.Scan() {\nreturn fmt.Errorf(\"%q returned empty\", cmd)\n}\n- if !scanner.Scan() {\n- return fmt.Errorf(\"%q returned empty\", cmd)\n+ if line := scanner.Text(); !strings.HasPrefix(line, \"POINTS (\") {\n+ return fmt.Errorf(\"%q missing POINTS header: %q\", cmd, line)\n+ }\n+ for scanner.Scan() {\n+ line := scanner.Text()\n+ if len(line) == 0 {\n+ continue // Skip empty lines.\n+ }\n+ if strings.HasPrefix(line, \"SINKS (\") {\n+ break // Starting SINKS section, POINTS section is over.\n}\n- for line := scanner.Text(); scanner.Scan(); line = scanner.Text() {\nelems := strings.Split(line, \",\")\nif len(elems) != 3 {\nreturn fmt.Errorf(\"invalid line: %q\", line)\n@@ -88,6 +98,9 @@ func (b *Builder) LoadAllPoints(runscPath string) error {\nContextFields: ctxFields,\n})\n}\n+ if len(b.points) == 0 {\n+ return fmt.Errorf(\"%q returned no points\", cmd)\n+ }\nreturn scanner.Err()\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add sinks to `runsc trace metadata` output Updates #4805 PiperOrigin-RevId: 465150097
259,868
03.08.2022 14:52:22
25,200
adc4b6b316869fcddcd4c771c5297cb749b134fb
BuildKite: Refactor Pipeline YAML. This adds templates that can be used to distinguish tests that rely on the checked-out source tree vs using STAGED_BINARIES instead.
[ { "change_type": "MODIFY", "old_path": ".buildkite/pipeline.yaml", "new_path": ".buildkite/pipeline.yaml", "diff": "@@ -7,6 +7,11 @@ _templates:\nlimit: 10\n- exit_status: \"*\"\nlimit: 2\n+ source_test: &source_test\n+ if: build.env(\"STAGED_BINARIES\") == null\n+ platform_specific_agents: &platform_specific_agents {}\n+ kvm_agents: &kvm_agents {kvm: \"true\"}\n+ ubuntu_agents: &ubuntu_agents {os: \"ubuntu\"}\nbenchmarks: &benchmarks\ntimeout_in_minutes: 120\nretry:\n@@ -21,8 +26,9 @@ _templates:\nBENCHMARKS_TABLE: benchmarks\nBENCHMARKS_UPLOAD: true\nagents:\n+ <<: *kvm_agents\n+ <<: *platform_specific_agents\narch: \"amd64\"\n- kvm: \"true\"\nnetstack_test: &netstack_test\nenv:\nPACKAGES: >\n@@ -42,31 +48,40 @@ env:\n# Force a clean checkout every time to avoid reuse of files between runs.\nBUILDKITE_CLEAN_CHECKOUT: true\n+ # Optional filter for syscall tests.\n+ SYSCALL_TEST_FILTERS: ''\n+\nsteps:\n# Run basic smoke tests before preceding to other tests.\n- <<: *common\n+ <<: *source_test\nlabel: \":fire: Smoke tests (AMD64)\"\ncommand: make smoke-tests\nagents:\narch: \"amd64\"\n- wait\n- <<: *common\n+ <<: *source_test\nlabel: \":fire: Smoke tests (ARM64)\"\ncommand: make smoke-tests\nagents:\narch: \"arm64\"\n- <<: *common\n+ <<: *source_test\nlabel: \":fire: Smoke race tests\"\ncommand: make smoke-race-tests\n+ - wait\n# Build everything.\n- <<: *common\n+ <<: *source_test\nlabel: \":world_map: Build everything (AMD64)\"\ncommand: \"make build OPTIONS=--build_tag_filters=-nogo TARGETS=//...\"\nagents:\narch: \"amd64\"\n- <<: *common\n+ <<: *source_test\nlabel: \":world_map: Build everything (ARM64)\"\ncommands:\n- \"make build OPTIONS=--build_tag_filters=-nogo TARGETS=//pkg/...\"\n@@ -78,6 +93,7 @@ steps:\n# as a GitHub action in order to preserve this maintaince across forks. However, providing the\n# action here may provide easier debuggability and diagnosis on failure.\n- <<: *common\n+ <<: *source_test\nlabel: \":golang: Go branch\"\ncommands:\n- tools/go_branch.sh\n@@ -86,6 +102,7 @@ steps:\n# Check that commonly used netstack packages build on various platforms.\n- <<: *common\n+ <<: *source_test\n<<: *netstack_test\nlabel: \":mac: Netstack on Mac\"\ncommands:\n@@ -93,6 +110,7 @@ steps:\n- git checkout go && git clean -xf .\n- GOOS=darwin GOARCH=arm64 go build $$PACKAGES\n- <<: *common\n+ <<: *source_test\n<<: *netstack_test\nlabel: \":windows: Netstack on Windows\"\ncommands:\n@@ -100,6 +118,7 @@ steps:\n- git checkout go && git clean -xf .\n- GOOS=windows GOARCH=amd64 go build $$PACKAGES\n- <<: *common\n+ <<: *source_test\n<<: *netstack_test\nlabel: \":freebsd: Netstack on FreeBSD\"\ncommands:\n@@ -107,6 +126,7 @@ steps:\n- git checkout go && git clean -xf .\n- GOOS=freebsd GOARCH=amd64 go build $$PACKAGES\n- <<: *common\n+ <<: *source_test\n<<: *netstack_test\nlabel: \":openbsd: Netstack on OpenBSD\"\ncommands:\n@@ -114,6 +134,7 @@ steps:\n- git checkout go && git clean -xf .\n- GOOS=openbsd GOARCH=amd64 go build $$PACKAGES\n- <<: *common\n+ <<: *source_test\n<<: *netstack_test\nlabel: \":older_man: Netstack on 32-bit Linux\"\ncommands:\n@@ -123,6 +144,7 @@ steps:\n# Release workflow.\n- <<: *common\n+ <<: *source_test\nlabel: \":ship: Release tests\"\ncommands:\n- make BAZEL_OPTIONS=--config=x86_64 artifacts/x86_64\n@@ -133,11 +155,13 @@ steps:\n# Images tests.\n- <<: *common\n+ <<: *source_test\nlabel: \":docker: Images (x86_64)\"\ncommand: make ARCH=x86_64 load-all-images\nagents:\narch: \"amd64\"\n- <<: *common\n+ <<: *source_test\nlabel: \":docker: Images (aarch64)\"\ncommand: make ARCH=aarch64 load-all-images\nagents:\n@@ -145,49 +169,60 @@ steps:\n# Basic unit tests.\n- <<: *common\n+ <<: *source_test\nlabel: \":golang: Nogo tests\"\ncommand: make nogo-tests\n- <<: *common\n+ <<: *source_test\nlabel: \":test_tube: Unit tests (cgroupv1)\"\ncommand: make unit-tests\nagents:\ncgroup: \"v1\"\narch: \"amd64\"\n- <<: *common\n+ <<: *source_test\nlabel: \":test_tube: Unit tests (cgroupv2)\"\ncommand: make unit-tests\nagents:\ncgroup: \"v2\"\narch: \"amd64\"\n- <<: *common\n+ <<: *source_test\nlabel: \":test_tube: Unit tests (ARM64)\"\ncommand: make unit-tests\nagents:\narch: \"arm64\"\n- <<: *common\n+ <<: *source_test\nlabel: \":test_tube: Container tests (cgroupv1)\"\ncommand: make container-tests\nagents:\n+ <<: *kvm_agents\ncgroup: \"v1\"\n- kvm: \"true\"\narch: \"amd64\"\n- <<: *common\n+ # This variant is not really a source test, but we annotate it as such to\n+ # avoid running binary-only tests for all variants of cgroups. It is\n+ # sufficient to run cgroupv2 variants only for source changes.\n+ <<: *source_test\nlabel: \":test_tube: Container tests (cgroupv2)\"\ncommand: make container-tests\nagents:\n+ <<: *kvm_agents\ncgroup: \"v2\"\n- kvm: \"true\"\narch: \"amd64\"\n# All system call tests.\n- <<: *common\nlabel: \":toolbox: System call tests (AMD64)\"\n- command: make syscall-tests\n+ command: \"make BAZEL_OPTIONS=--test_tag_filters=$SYSCALL_TEST_FILTERS syscall-tests\"\nparallelism: 20\nagents:\n+ <<: *platform_specific_agents\n+ <<: *kvm_agents\narch: \"amd64\"\n- kvm: \"true\"\n- <<: *common\n+ <<: *source_test\nlabel: \":muscle: System call tests (ARM64)\"\ncommand: make BAZEL_OPTIONS=--test_tag_filters=runsc_ptrace syscall-tests\nparallelism: 10\n@@ -196,99 +231,117 @@ steps:\n# Integration tests.\n- <<: *common\n+ <<: *source_test\nlabel: \":docker: Docker tests (cgroupv1)\"\ncommand: make docker-tests\nagents:\n+ <<: *ubuntu_agents\narch: \"amd64\"\ncgroup: \"v1\"\n- os: \"ubuntu\"\n- <<: *common\n+ # See above: not truly a source test.\n+ <<: *source_test\nlabel: \":docker: Docker tests (cgroupv2)\"\ncommand: make docker-tests\nagents:\n+ <<: *ubuntu_agents\narch: \"amd64\"\ncgroup: \"v2\"\n- os: \"ubuntu\"\n- <<: *common\nlabel: \":goggles: Overlay tests\"\ncommand: make overlay-tests\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\narch: \"amd64\"\n- os: \"ubuntu\"\n- <<: *common\nlabel: \":safety_pin: Host network tests\"\ncommand: make hostnet-tests\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\narch: \"amd64\"\n- os: \"ubuntu\"\n- <<: *common\nlabel: \":satellite: gVisor GSO tests\"\ncommand: make swgso-tests\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\narch: \"amd64\"\n- os: \"ubuntu\"\n- <<: *common\n+ <<: *source_test\nlabel: \":coffee: Do tests\"\ncommand: make do-tests\nagents:\narch: \"amd64\"\n- <<: *common\n+ <<: *source_test\nlabel: \":person_in_lotus_position: KVM tests\"\ncommand: make kvm-tests\nagents:\n+ <<: *kvm_agents\narch: \"amd64\"\n- kvm: \"true\"\n- <<: *common\nlabel: \":weight_lifter: Fsstress test\"\ncommand: make fsstress-test\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\narch: \"amd64\"\n- os: \"ubuntu\"\n- <<: *common\nlabel: \":docker: Containerd 1.3.9 tests\"\ncommand: make containerd-test-1.3.9\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\ncgroup: \"v1\"\narch: \"amd64\"\n- os: \"ubuntu\"\n- <<: *common\nlabel: \":docker: Containerd 1.4.3 tests\"\ncommand: make containerd-test-1.4.3\nagents:\n- os: \"ubuntu\"\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\n- <<: *common\nlabel: \":docker: Containerd 1.5.4 tests (cgroupv1)\"\ncommand: make containerd-test-1.5.4\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\ncgroup: \"v1\"\n- os: \"ubuntu\"\n- <<: *common\n+ # See above: not truly a source test.\n+ <<: *source_test\nlabel: \":docker: Containerd 1.5.4 tests (cgroupv2)\"\ncommand: make containerd-test-1.5.4\nagents:\n+ <<: *ubuntu_agents\ncgroup: \"v2\"\n- os: \"ubuntu\"\n- <<: *common\nlabel: \":docker: Containerd 1.6.0-rc.4 tests (cgroupv1)\"\ncommand: make containerd-test-1.6.0-rc.4\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\ncgroup: \"v1\"\n- os: \"ubuntu\"\n- <<: *common\n+ <<: *source_test\nlabel: \":docker: Containerd 1.6.0-rc.4 tests (cgroupv2)\"\ncommand: make containerd-test-1.6.0-rc.4\nagents:\n+ <<: *ubuntu_agents\ncgroup: \"v2\"\n- os: \"ubuntu\"\n- <<: *common\n+ <<: *source_test\nlabel: \":podman: Podman\"\ncommand: sudo ./test/podman/run.sh\nagents:\n+ <<: *ubuntu_agents\ncgroup: \"v2\"\n- os: \"ubuntu\"\n# Check the website builds.\n- <<: *common\n+ <<: *source_test\nlabel: \":earth_americas: Website tests\"\ncommand: make website-build\nagents:\n@@ -296,20 +349,23 @@ steps:\n# Networking tests.\n- <<: *common\n+ <<: *source_test\nlabel: \":table_tennis_paddle_and_ball: IPTables tests\"\ncommand: make iptables-tests\nagents:\n- os: \"ubuntu\"\n+ <<: *ubuntu_agents\n- <<: *common\n+ <<: *source_test\nlabel: \":construction_worker: Packetdrill tests\"\ncommand: make packetdrill-tests\nagents:\n- os: \"ubuntu\"\n+ <<: *ubuntu_agents\n- <<: *common\n+ <<: *source_test\nlabel: \":hammer: Packetimpact tests\"\ncommand: make packetimpact-tests\nagents:\n- os: \"ubuntu\"\n+ <<: *ubuntu_agents\n# Runtime tests.\n- <<: *common\n@@ -317,36 +373,41 @@ steps:\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} php8.1.1-runtime-tests\nparallelism: 10\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\narch: \"amd64\"\n- os: \"ubuntu\"\n- <<: *common\nlabel: \":java: Java runtime tests\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} java17-runtime-tests\nparallelism: 40\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\narch: \"amd64\"\n- os: \"ubuntu\"\n- <<: *common\nlabel: \":golang: Go runtime tests\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} go1.16-runtime-tests\nparallelism: 10\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\narch: \"amd64\"\n- os: \"ubuntu\"\n- <<: *common\nlabel: \":node: NodeJS runtime tests\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} nodejs16.13.2-runtime-tests\nparallelism: 10\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\narch: \"amd64\"\n- os: \"ubuntu\"\n- <<: *common\nlabel: \":python: Python runtime tests\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} python3.10.2-runtime-tests\nparallelism: 10\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\narch: \"amd64\"\n- os: \"ubuntu\"\n# Runtime tests (LISAFS).\n- <<: *common\n@@ -355,40 +416,45 @@ steps:\nparallelism: 10\nif: build.message =~ /lisafs/ || build.branch == \"master\"\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\narch: \"amd64\"\n- os: \"ubuntu\"\n- <<: *common\nlabel: \":java: Java runtime tests (LISAFS)\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} java17-runtime-tests_lisafs\nparallelism: 40\nif: build.message =~ /lisafs/ || build.branch == \"master\"\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\narch: \"amd64\"\n- os: \"ubuntu\"\n- <<: *common\nlabel: \":golang: Go runtime tests (LISAFS)\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} go1.16-runtime-tests_lisafs\nparallelism: 10\nif: build.message =~ /lisafs/ || build.branch == \"master\"\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\narch: \"amd64\"\n- os: \"ubuntu\"\n- <<: *common\nlabel: \":node: NodeJS runtime tests (LISAFS)\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} nodejs16.13.2-runtime-tests_lisafs\nparallelism: 10\nif: build.message =~ /lisafs/ || build.branch == \"master\"\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\narch: \"amd64\"\n- os: \"ubuntu\"\n- <<: *common\nlabel: \":python: Python runtime tests (LISAFS)\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} python3.10.2-runtime-tests_lisafs\nparallelism: 10\nif: build.message =~ /lisafs/ || build.branch == \"master\"\nagents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\narch: \"amd64\"\n- os: \"ubuntu\"\n# Run basic benchmarks smoke tests (no upload).\n- <<: *common\n@@ -397,8 +463,9 @@ steps:\n# Use the opposite of the benchmarks filter.\nif: build.branch != \"master\"\nagents:\n+ <<: *platform_specific_agents\n+ <<: *kvm_agents\narch: \"amd64\"\n- kvm: \"true\"\n# Run all benchmarks.\n- <<: *benchmarks\n@@ -413,7 +480,7 @@ steps:\n# For fio, running with --test.benchtime=Xs scales the written/read\n# bytes to several GB. This is not a problem for root/bind/volume mounts,\n# but for tmpfs mounts, the size can grow to more memory than the machine\n- # has availabe. Fix the runs to 1GB written/read for the benchmark.\n+ # has available. Fix the runs to 1GB written/read for the benchmark.\n- <<: *benchmarks\nlabel: \":floppy_disk: FIO benchmarks (read/write)\"\ncommand: make -i benchmark-platforms BENCHMARKS_SUITE=fio BENCHMARKS_TARGETS=test/benchmarks/fs:fio_test BENCHMARKS_FILTER=Fio/operation\\.[rw][er] BENCHMARKS_OPTIONS=--test.benchtime=1000x\n" } ]
Go
Apache License 2.0
google/gvisor
BuildKite: Refactor Pipeline YAML. This adds templates that can be used to distinguish tests that rely on the checked-out source tree vs using STAGED_BINARIES instead. PiperOrigin-RevId: 465155335
259,992
03.08.2022 15:26:45
25,200
e8c45a17cf34b130af3bc50da5cc0d9ab8b9b021
Enable test/trace:trace_test It was mistakenly marked as manual. Updates
[ { "change_type": "MODIFY", "old_path": "test/trace/BUILD", "new_path": "test/trace/BUILD", "diff": "@@ -13,7 +13,6 @@ go_test(\nlibrary = \":trace\",\ntags = [\n\"local\",\n- \"manual\",\n],\ndeps = [\n\"//pkg/sentry/seccheck\",\n" }, { "change_type": "MODIFY", "old_path": "test/trace/trace_test.go", "new_path": "test/trace/trace_test.go", "diff": "@@ -108,6 +108,14 @@ func matchPoints(t *testing.T, msgs []test.Message) {\npb.MessageType_MESSAGE_SYSCALL_RAW: {checker: checkSyscallRaw},\npb.MessageType_MESSAGE_SYSCALL_READ: {checker: checkSyscallRead},\npb.MessageType_MESSAGE_SYSCALL_SOCKET: {checker: checkSyscallSocket},\n+\n+ // TODO(gvisor.dev/issue/4805): Add validation for these messages.\n+ pb.MessageType_MESSAGE_SYSCALL_ACCEPT: {checker: checkTODO},\n+ pb.MessageType_MESSAGE_SYSCALL_BIND: {checker: checkTODO},\n+ pb.MessageType_MESSAGE_SYSCALL_CLONE: {checker: checkTODO},\n+ pb.MessageType_MESSAGE_SYSCALL_DUP: {checker: checkTODO},\n+ pb.MessageType_MESSAGE_SYSCALL_PIPE: {checker: checkTODO},\n+ pb.MessageType_MESSAGE_SYSCALL_PRLIMIT64: {checker: checkTODO},\n}\nfor _, msg := range msgs {\nt.Logf(\"Processing message type %v\", msg.MsgType)\n@@ -433,3 +441,7 @@ func checkSyscallSocket(msg test.Message) error {\n}\nreturn nil\n}\n+\n+func checkTODO(_ test.Message) error {\n+ return nil\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Enable test/trace:trace_test It was mistakenly marked as manual. Updates #4805 PiperOrigin-RevId: 465163546
259,909
04.08.2022 14:26:09
25,200
2f34113ec1cdceafb6b6480633539f68b376446d
Add a flag to tcp_benchmarks that runs the workload over ipv6.
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/tcp/BUILD", "new_path": "test/benchmarks/tcp/BUILD", "diff": "@@ -13,7 +13,9 @@ go_binary(\n\"//pkg/tcpip/link/qdisc/fifo\",\n\"//pkg/tcpip/network/arp\",\n\"//pkg/tcpip/network/ipv4\",\n+ \"//pkg/tcpip/network/ipv6\",\n\"//pkg/tcpip/stack\",\n+ \"//pkg/tcpip/transport/icmp\",\n\"//pkg/tcpip/transport/tcp\",\n\"//pkg/tcpip/transport/udp\",\n\"@org_golang_x_sys//unix:go_default_library\",\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/tcp/tcp_benchmark.sh", "new_path": "test/benchmarks/tcp/tcp_benchmark.sh", "diff": "# Fixed parameters.\niperf_port=45201 # Not likely to be privileged.\nproxy_port=44000 # Ditto.\n+mask=8\n+\nclient_addr=10.0.0.1\nclient_proxy_addr=10.0.0.2\nserver_proxy_addr=10.0.0.3\nserver_addr=10.0.0.4\n-mask=8\n+full_server_addr=${server_addr}:${iperf_port}\n+full_server_proxy_addr=${server_proxy_addr}:${proxy_port}\n+iperf_version_arg=\n# Defaults; this provides a reasonable approximation of a decent internet link.\n# Parameters can be varied independently from this set to see response to\n@@ -140,6 +144,16 @@ while [ $# -gt 0 ]; do\n--disable-linux-gro)\ndisable_linux_gro=1\n;;\n+ --ipv6)\n+ client_addr=fd::1\n+ client_proxy_addr=fd::2\n+ server_proxy_addr=fd::3\n+ server_addr=fd::4\n+ full_server_addr=[${server_addr}]:${iperf_port}\n+ full_server_proxy_addr=[${server_proxy_addr}]:${proxy_port}\n+ iperf_version_arg=-V\n+ netstack_opts=\"${netstack_opts} -ipv6\"\n+ ;;\n--num-client-threads)\nshift\nnum_client_threads=$1\n@@ -171,6 +185,7 @@ while [ $# -gt 0 ]; do\necho \" --num-client-threads number of parallel client threads to run\"\necho \" --disable-linux-gso disable segmentation offload (TSO, GSO, GRO) in the Linux network stack\"\necho \" --disable-linux-gro disable GRO in the Linux network stack\"\n+ echo \" --ipv6 use ipv6 for benchmarks\"\necho \"\"\necho \"The output will of the script will be:\"\necho \" <throughput> <client-cpu-usage> <server-cpu-usage>\"\n@@ -213,24 +228,24 @@ fi\n# Client proxy that will listen on the client's iperf target forward traffic\n# using the host networking stack.\n-client_args=\"${proxy_binary} -port ${proxy_port} -forward ${server_proxy_addr}:${proxy_port}\"\n+client_args=\"${proxy_binary} -port ${proxy_port} -forward ${full_server_proxy_addr}\"\nif ${client}; then\n# Client proxy that will listen on the client's iperf target\n# and forward traffic using netstack.\nclient_args=\"${proxy_binary} ${netstack_opts} -port ${proxy_port} -client \\\\\n-mtu ${mtu} -iface client.0 -addr ${client_proxy_addr} -mask ${mask} \\\\\n- -forward ${server_proxy_addr}:${proxy_port} -gso=${gso} -swgso=${swgso}\"\n+ -forward ${full_server_proxy_addr} -gso=${gso} -swgso=${swgso}\"\nfi\n# Server proxy that will listen on the proxy port and forward to the server's\n# iperf server using the host networking stack.\n-server_args=\"${proxy_binary} -port ${proxy_port} -forward ${server_addr}:${iperf_port}\"\n+server_args=\"${proxy_binary} -port ${proxy_port} -forward ${full_server_addr}\"\nif ${server}; then\n# Server proxy that will listen on the proxy port and forward to the servers'\n# iperf server using netstack.\nserver_args=\"${proxy_binary} ${netstack_opts} -port ${proxy_port} -server \\\\\n-mtu ${mtu} -iface server.0 -addr ${server_proxy_addr} -mask ${mask} \\\\\n- -forward ${server_addr}:${iperf_port} -gso=${gso} -swgso=${swgso}\"\n+ -forward ${full_server_addr} -gso=${gso} -swgso=${swgso}\"\nfi\n# Specify loss and duplicate parameters only if they are non-zero\n@@ -344,15 +359,19 @@ ${nsjoin_binary} /tmp/server.netns ip link set lo up\nip link set dev client.1 up\nip link set dev server.1 up\n-${nsjoin_binary} /tmp/client.netns ${client_args} &\n-client_pid=\\$!\n${nsjoin_binary} /tmp/server.netns ${server_args} &\nserver_pid=\\$!\n# Start the iperf server.\n-${nsjoin_binary} /tmp/server.netns iperf -p ${iperf_port} -s >&2 &\n+${nsjoin_binary} /tmp/server.netns iperf ${iperf_version_arg} -p ${iperf_port} -s >&2 &\niperf_pid=\\$!\n+# Give services time to start.\n+sleep 5\n+\n+${nsjoin_binary} /tmp/client.netns ${client_args} &\n+client_pid=\\$!\n+\n# Show traffic information.\nif ! ${client} && ! ${server}; then\n${nsjoin_binary} /tmp/client.netns ping -c 100 -i 0.001 -W 1 ${server_addr} >&2 || true\n@@ -374,7 +393,7 @@ trap cleanup EXIT\n# Run the benchmark, recording the results file.\nwhile ${nsjoin_binary} /tmp/client.netns iperf \\\\\n- -p ${proxy_port} -c ${client_addr} -t ${duration} -f m -P ${num_client_threads} 2>&1 \\\\\n+ ${iperf_version_arg} -p ${proxy_port} -c ${client_addr} -t ${duration} -f m -P ${num_client_threads} 2>&1 \\\\\n| tee \\$results_file \\\\\n| grep \"connect failed\" >/dev/null; do\nsleep 0.1 # Wait for all services.\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/tcp/tcp_proxy.go", "new_path": "test/benchmarks/tcp/tcp_proxy.go", "diff": "@@ -38,7 +38,9 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/link/qdisc/fifo\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/arp\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv4\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/network/ipv6\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/transport/icmp\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/tcp\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/udp\"\n)\n@@ -64,6 +66,7 @@ var (\nserverTCPProbeFile = flag.String(\"server_tcp_probe_file\", \"\", \"if specified, installs a tcp probe to dump endpoint state to the specified file.\")\ncpuprofile = flag.String(\"cpuprofile\", \"\", \"write cpu profile to the specified file.\")\nmemprofile = flag.String(\"memprofile\", \"\", \"write memory profile to the specified file.\")\n+ useIpv6 = flag.Bool(\"ipv6\", false, \"use ipv6 instead of ipv4.\")\n)\ntype impl interface {\n@@ -156,26 +159,37 @@ func newNetstackImpl(mode string) (impl, error) {\n// Parse details.\nparsedAddr := tcpip.Address(net.ParseIP(*addr).To4())\n+ if *useIpv6 {\n+ parsedAddr = tcpip.Address(net.ParseIP(*addr).To16())\n+ }\nparsedDest := tcpip.Address(\"\") // Filled in below.\nparsedMask := tcpip.AddressMask(\"\") // Filled in below.\n+ parsedDest6 := tcpip.Address(\"\") // Filled in below.\n+ parsedMask6 := tcpip.AddressMask(\"\") // Filled in below.\nswitch *mask {\ncase 8:\nparsedDest = tcpip.Address([]byte{parsedAddr[0], 0, 0, 0})\nparsedMask = tcpip.AddressMask([]byte{0xff, 0, 0, 0})\n+ parsedDest6 = tcpip.Address(append([]byte{parsedAddr[0]}, make([]byte, 15)...))\n+ parsedMask6 = tcpip.AddressMask(append([]byte{0xff}, make([]byte, 15)...))\ncase 16:\nparsedDest = tcpip.Address([]byte{parsedAddr[0], parsedAddr[1], 0, 0})\nparsedMask = tcpip.AddressMask([]byte{0xff, 0xff, 0, 0})\n+ parsedDest6 = tcpip.Address(append([]byte{parsedAddr[0], parsedAddr[1]}, make([]byte, 14)...))\n+ parsedMask6 = tcpip.AddressMask(append([]byte{0xff, 0xff}, make([]byte, 14)...))\ncase 24:\nparsedDest = tcpip.Address([]byte{parsedAddr[0], parsedAddr[1], parsedAddr[2], 0})\nparsedMask = tcpip.AddressMask([]byte{0xff, 0xff, 0xff, 0})\n+ parsedDest6 = tcpip.Address(append([]byte{parsedAddr[0], parsedAddr[1], parsedAddr[2]}, make([]byte, 13)...))\n+ parsedMask6 = tcpip.AddressMask(append([]byte{0xff, 0xff, 0xff}, make([]byte, 13)...))\ndefault:\n// This is just laziness; we don't expect a different mask.\nreturn nil, fmt.Errorf(\"mask %d not supported\", mask)\n}\n// Create a new network stack.\n- netProtos := []stack.NetworkProtocolFactory{ipv4.NewProtocol, arp.NewProtocol}\n- transProtos := []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol}\n+ netProtos := []stack.NetworkProtocolFactory{ipv6.NewProtocol, ipv4.NewProtocol, arp.NewProtocol}\n+ transProtos := []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol, icmp.NewProtocol4, icmp.NewProtocol6}\ns := stack.New(stack.Options{\nNetworkProtocols: netProtos,\nTransportProtocols: transProtos,\n@@ -210,22 +224,35 @@ func newNetstackImpl(mode string) (impl, error) {\nif err := s.CreateNICWithOptions(nicID, ep, opts); err != nil {\nreturn nil, fmt.Errorf(\"error creating NIC %q: %v\", *iface, err)\n}\n+ proto := ipv4.ProtocolNumber\n+ if *useIpv6 {\n+ proto = ipv6.ProtocolNumber\n+ }\nprotocolAddr := tcpip.ProtocolAddress{\n- Protocol: ipv4.ProtocolNumber,\n+ Protocol: proto,\nAddressWithPrefix: parsedAddr.WithPrefix(),\n}\nif err := s.AddProtocolAddress(nicID, protocolAddr, stack.AddressProperties{}); err != nil {\nreturn nil, fmt.Errorf(\"error adding IP address %+v to %q: %s\", protocolAddr, *iface, err)\n}\n- subnet, err := tcpip.NewSubnet(parsedDest, parsedMask)\n+ subnet4, err := tcpip.NewSubnet(parsedDest, parsedMask)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"tcpip.Subnet(%s, %s): %s\", parsedDest, parsedMask, err)\n+ }\n+ subnet6, err := tcpip.NewSubnet(parsedDest6, parsedMask6)\nif err != nil {\nreturn nil, fmt.Errorf(\"tcpip.Subnet(%s, %s): %s\", parsedDest, parsedMask, err)\n}\n+\n// Add default route; we only support\ns.SetRouteTable([]tcpip.Route{\n{\n- Destination: subnet,\n+ Destination: subnet4,\n+ NIC: nicID,\n+ },\n+ {\n+ Destination: subnet6,\nNIC: nicID,\n},\n})\n@@ -281,12 +308,20 @@ func (n netstackImpl) dial(address string) (net.Conn, error) {\nif err != nil {\nreturn nil, err\n}\n+ hostAddr := net.ParseIP(host).To4()\n+ if *useIpv6 {\n+ hostAddr = net.ParseIP(host).To16()\n+ }\naddr := tcpip.FullAddress{\nNIC: nicID,\n- Addr: tcpip.Address(net.ParseIP(host).To4()),\n+ Addr: tcpip.Address(hostAddr),\nPort: uint16(portNumber),\n}\n- conn, err := gonet.DialTCP(n.s, addr, ipv4.ProtocolNumber)\n+ proto := ipv4.ProtocolNumber\n+ if *useIpv6 {\n+ proto = ipv6.ProtocolNumber\n+ }\n+ conn, err := gonet.DialTCP(n.s, addr, proto)\nif err != nil {\nreturn nil, err\n}\n@@ -298,7 +333,11 @@ func (n netstackImpl) listen(port int) (net.Listener, error) {\nNIC: nicID,\nPort: uint16(port),\n}\n- listener, err := gonet.ListenTCP(n.s, addr, ipv4.ProtocolNumber)\n+ proto := ipv4.ProtocolNumber\n+ if *useIpv6 {\n+ proto = ipv6.ProtocolNumber\n+ }\n+ listener, err := gonet.ListenTCP(n.s, addr, proto)\nif err != nil {\nreturn nil, err\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add a flag to tcp_benchmarks that runs the workload over ipv6. PiperOrigin-RevId: 465404721
259,868
05.08.2022 12:38:08
25,200
86059124df31971e07da40395a2c4225f004dc40
`gvisor.dev`: Update documentation around platforms. Explain the consequences of using KVM in a nested virtualization environment. Mention GKE Sandbox proprietary platform. Fix command to check if the user is part of the `kvm` group. Small fixes here and there.
[ { "change_type": "MODIFY", "old_path": "g3doc/architecture_guide/platforms.md", "new_path": "g3doc/architecture_guide/platforms.md", "diff": "gVisor requires a platform to implement interception of syscalls, basic context\nswitching, and memory mapping functionality. Internally, gVisor uses an\n-abstraction sensibly called [Platform][platform]. A simplified version of this\n+abstraction sensibly called [`Platform`][platform]. A simplified version of this\ninterface looks like:\n```golang\n@@ -29,14 +29,15 @@ various trade-offs, generally around performance and hardware requirements.\n## Implementations\nThe choice of platform depends on the context in which `runsc` is executing. In\n-general, virtualized platforms may be limited to platforms that do not require\n-hardware virtualized support (since the hardware is already in use):\n+general, when running on bare-metal (not inside a VM), the KVM platform will\n+provide the best performance. The `ptrace` platform is a better choice when\n+running inside a VM, or on a machine without virtualization support.\n![Platforms](platforms.png \"Platform examples.\")\n### ptrace\n-The ptrace platform uses [PTRACE_SYSEMU][ptrace] to execute user code without\n+The ptrace platform uses [`PTRACE_SYSEMU`][ptrace] to execute user code without\nallowing it to execute host system calls. This platform can run anywhere that\n`ptrace` works (even VMs without nested virtualization), which is ubiquitous.\n@@ -46,12 +47,21 @@ call-heavy applications may pay a [performance penalty](./performance.md).\n### KVM\nThe KVM platform uses the kernel's [KVM][kvm] functionality to allow the Sentry\n-to act as both guest OS and VMM. The KVM platform can run on bare-metal or in a\n+to act as both guest OS and VMM. The KVM platform can run on bare-metal, or in a\nVM with nested virtualization enabled. While there is no virtualized hardware\nlayer -- the sandbox retains a process model -- gVisor leverages virtualization\nextensions available on modern processors in order to improve isolation and\nperformance of address space switches.\n+Note that while running within a nested VM is feasible with the KVM platform,\n+the `ptrace` platform will often provide better performance in such a setup, due\n+to the overhead of nested virtualization.\n+\n+### GKE Sandbox\n+\n+[GKE Sandbox] uses a custom gVisor platform implementation which provides better\n+performance than `ptrace` and KVM.\n+\n## Changing Platforms\nSee [Changing Platforms](../user_guide/platforms.md).\n@@ -59,3 +69,4 @@ See [Changing Platforms](../user_guide/platforms.md).\n[kvm]: https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt\n[platform]: https://cs.opensource.google/gvisor/gvisor/+/release-20190304.1:pkg/sentry/platform/platform.go;l=33\n[ptrace]: http://man7.org/linux/man-pages/man2/ptrace.2.html\n+[GKE Sandbox]: https://cloud.google.com/kubernetes-engine/docs/concepts/sandbox-pods\n" }, { "change_type": "MODIFY", "old_path": "g3doc/user_guide/platforms.md", "new_path": "g3doc/user_guide/platforms.md", "diff": "@@ -11,21 +11,24 @@ If you intend to run the KVM platform, you will also to have KVM installed on\nyour system. If you are running a Debian based system like Debian or Ubuntu you\ncan usually do this by ensuring the module is loaded, and your user has\npermissions to access the `/dev/kvm` device. Usually, it means that the user is\n-in the kvm group.\n+in the `kvm` group.\n-```bash\n+```shell\n# Check that /dev/kvm is owned by the kvm group\n$ ls -l /dev/kvm\ncrw-rw----+ 1 root kvm 10, 232 Jul 26 00:04 /dev/kvm\n# Make sure that the current user is part of the kvm group\n-$ $ groups | grep -q kvm | echo ok\n+$ groups | grep -qw kvm && echo ok\nok\n```\n-If you are using a virtual machine you will need to make sure that nested\n-virtualization is configured. Here are links to documents on how to set up\n-nested virtualization in several popular environments:\n+**For best performance, use the KVM platform on bare-metal machines only**. If\n+you have to run gVisor within a virtual machine, the `ptrace` platform will\n+often yield better performance than KVM. If you still want to use KVM within a\n+virtual machine, you will need to make sure that nested virtualization is\n+configured. Here are links to documents on how to set up nested virtualization\n+in several popular environments:\n* Google Cloud: [Enabling Nested Virtualization for VM Instances][nested-gcp]\n* Microsoft Azure:\n" } ]
Go
Apache License 2.0
google/gvisor
`gvisor.dev`: Update documentation around platforms. - Explain the consequences of using KVM in a nested virtualization environment. - Mention GKE Sandbox proprietary platform. - Fix command to check if the user is part of the `kvm` group. - Small fixes here and there. PiperOrigin-RevId: 465625190
259,868
05.08.2022 14:55:22
25,200
a91c5c4b4ceb3fa4216c86d560665f21a6ec6eaf
`gvisor.dev`: Update WordPress example to recommend not sandboxing the database.
[ { "change_type": "MODIFY", "old_path": "g3doc/user_guide/tutorials/docker-compose.md", "new_path": "g3doc/user_guide/tutorials/docker-compose.md", "diff": "@@ -16,7 +16,14 @@ We will specify two services, a `wordpress` service for the Wordpress Apache\nserver, and a `db` service for MySQL. We will configure Wordpress to connect to\nMySQL via the `db` service host name.\n-> **Note:** Docker Compose uses it's own network by default and allows services\n+> **Note**: This example uses gVisor to sandbox the frontend web server, but not\n+> the MySQL database backend. In a production setup, due to\n+> [the I/O overhead](../../architecture_guide/performance) imposed by gVisor,\n+> **it is not recommended to run your database in a sandbox**. The frontend is\n+> the critical component with the largest outside attack surface, where gVisor's\n+> security/performance trade-off makes the most sense.\n+\n+> **Note**: Docker Compose uses it's own network by default and allows services\n> to communicate using their service name. Docker Compose does this by setting\n> up a DNS server at IP address 127.0.0.11 and configuring containers to use it\n> via [resolv.conf][resolv.conf]. This IP is not addressable inside a gVisor\n@@ -24,7 +31,7 @@ MySQL via the `db` service host name.\n> `8.8.8.8` and use a network that allows routing to it. See\n> [Networking in Compose][compose-networking] for more details.\n-> **Note:** The `runtime` field was removed from services in the 3.x version of\n+> **Note**: The `runtime` field was removed from services in the 3.x version of\n> the API in versions of docker-compose < 1.27.0. You will need to write your\n> `docker-compose.yaml` file using the 2.x format or use docker-compose >=\n> 1.27.0. See this [issue](https://github.com/docker/compose/issues/6239) for\n@@ -46,6 +53,8 @@ services:\nMYSQL_PASSWORD: wordpress\n# All services must be on the same network to communicate.\nnetwork_mode: \"bridge\"\n+ # Uncomment the following line if you want to sandbox the database.\n+ #runtime: \"runsc\"\nwordpress:\ndepends_on:\n" }, { "change_type": "MODIFY", "old_path": "g3doc/user_guide/tutorials/docker.md", "new_path": "g3doc/user_guide/tutorials/docker.md", "diff": "@@ -13,6 +13,13 @@ document assumes that the runtime name chosen is `runsc`.\nNow, let's deploy a WordPress site using Docker. WordPress site requires two\ncontainers: web server in the frontend, MySQL database in the backend.\n+> **Note**: This example uses gVisor to sandbox the frontend web server, but not\n+> the MySQL database backend. In a production setup, due to\n+> [the I/O overhead](../../architecture_guide/performance) imposed by gVisor,\n+> **it is not recommended to run your database in a sandbox**. The frontend is\n+> the critical component with the largest outside attack surface, where gVisor's\n+> security/performance trade-off makes the most sense.\n+\nFirst, let's define a few environment variables that are shared between both\ncontainers:\n@@ -25,8 +32,9 @@ export MYSQL_USER=wordpress\nNext, let's start the database container running MySQL and wait until the\ndatabase is initialized:\n-```bash\n-docker run --runtime=runsc --name mysql -d \\\n+```shell\n+# If you want to sandbox the database, add --runtime=runsc to this command.\n+$ docker run --name mysql -d \\\n-e MYSQL_RANDOM_ROOT_PASSWORD=1 \\\n-e MYSQL_PASSWORD=\"${MYSQL_PASSWORD}\" \\\n-e MYSQL_DATABASE=\"${MYSQL_DB}\" \\\n@@ -34,15 +42,15 @@ docker run --runtime=runsc --name mysql -d \\\nmysql:5.7\n# Wait until this message appears in the log.\n-docker logs mysql |& grep 'port: 3306 MySQL Community Server (GPL)'\n+$ docker logs mysql |& grep 'port: 3306 MySQL Community Server (GPL)'\n```\nOnce the database is running, you can start the WordPress frontend. We use the\n`--link` option to connect the frontend to the database, and expose the\nWordPress to port 8080 on the localhost.\n-```bash\n-docker run --runtime=runsc --name wordpress -d \\\n+```shell\n+$ docker run --runtime=runsc --name wordpress -d \\\n--link mysql:mysql \\\n-p 8080:80 \\\n-e WORDPRESS_DB_HOST=mysql \\\n@@ -56,7 +64,8 @@ docker run --runtime=runsc --name wordpress -d \\\nNow, you can access the WordPress website pointing your favorite browser to\n<http://localhost:8080>.\n-Congratulations! You have just deployed a WordPress site using Docker.\n+Congratulations! You have just deployed a WordPress site using Docker and\n+gVisor.\n### What's next\n" }, { "change_type": "MODIFY", "old_path": "g3doc/user_guide/tutorials/kubernetes.md", "new_path": "g3doc/user_guide/tutorials/kubernetes.md", "diff": "@@ -48,6 +48,13 @@ two pods: web server in the frontend, MySQL database in the backend. Both\napplications use PersistentVolumes to store the site data data. In addition,\nthey use secret store to share MySQL password between them.\n+> **Note**: This example uses gVisor to sandbox the frontend web server, but not\n+> the MySQL database backend. In a production setup, due to\n+> [the I/O overhead](../../architecture_guide/performance) imposed by gVisor,\n+> **it is not recommended to run your database in a sandbox**. The frontend is\n+> the critical component with the largest outside attack surface, where gVisor's\n+> security/performance trade-off makes the most sense.\n+\nFirst, let's download the deployment configuration files to add the runtime\nclass annotation to them:\n@@ -181,7 +188,7 @@ spec:\napp: wordpress\ntier: mysql\nspec:\n- runtimeClassName: gvisor # ADD THIS LINE\n+ #runtimeClassName: gvisor # Uncomment this line if you want to sandbox the database.\ncontainers:\n- image: mysql:5.6\nname: mysql\n" } ]
Go
Apache License 2.0
google/gvisor
`gvisor.dev`: Update WordPress example to recommend not sandboxing the database. PiperOrigin-RevId: 465654131
259,868
05.08.2022 19:06:59
25,200
919910ce670a680ec9b9438c8087884b16385b03
Fix d3-based performance graphs in Firefox. Reported by Thomas Gleixner in
[ { "change_type": "MODIFY", "old_path": "website/_includes/footer.html", "new_path": "website/_includes/footer.html", "diff": "{% include footer-links.html %}\n</footer>\n-<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\" integrity=\"sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=\" crossorigin=\"anonymous\"></script>\n-<script src=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.1/js/all.min.js\" integrity=\"sha256-Z1Nvg/+y2+vRFhFgFij7Lv0r77yG3hOvWz2wI0SfTa0=\" crossorigin=\"anonymous\"></script>\n-<script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js\" integrity=\"sha256-U5ZEeKfGNOja007MMD3YBI0A3OSZOQbeG6z2f2Y0hu8=\" crossorigin=\"anonymous\"></script>\n-<script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js\" integrity=\"sha256-hYXbQJK4qdJiAeDVjjQ9G0D6A0xLnDQ4eJI9dkm7Fpk=\" crossorigin=\"anonymous\"></script>\n-\n{% if site.analytics %}\n<script>\nvar doNotTrack = false;\n" }, { "change_type": "MODIFY", "old_path": "website/_includes/graph.html", "new_path": "website/_includes/graph.html", "diff": "{::nomarkdown}\n{% assign fn = include.id | remove: \" \" | remove: \"-\" | downcase %}\n-<figure><a href=\"{{ include.url }}\"><svg id=\"{{ include.id }}\" width=500 height=200 onload=\"render_{{ fn }}()\"><title>{{ include.title }}</title></svg></a></figure>\n+<figure><a href=\"{{ include.url }}\"><svg id=\"{{ include.id }}\" width=500 height=200><title>{{ include.title }}</title></svg></a></figure>\n<script>\nfunction render_{{ fn }}() {\nd3.csv(\"{{ include.url }}\", function(d, i, columns) {\n@@ -201,5 +201,6 @@ d3.csv(\"{{ include.url }}\", function(d, i, columns) {\n.text(function(d) { return d; });\n});\n}\n+$(render_{{ fn }});\n</script>\n{:/}\n" }, { "change_type": "MODIFY", "old_path": "website/_includes/header.html", "new_path": "website/_includes/header.html", "diff": "<!-- Dependencies. -->\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css\" integrity=\"sha256-916EbMg70RQy9LHiGkXzG8hSg9EdNy97GazNG/aiY1w=\" crossorigin=\"anonymous\" />\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.1/css/all.min.css\" integrity=\"sha256-fdcFNFiBMrNfWL6OcAGQz6jDgNTRxnrLEd4vJYFWScE=\" crossorigin=\"anonymous\" />\n+ {% include scripts.html %}\n<!-- Our own style sheet. -->\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/main.css\">\n" }, { "change_type": "ADD", "old_path": null, "new_path": "website/_includes/scripts.html", "diff": "+<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\" integrity=\"sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=\" crossorigin=\"anonymous\"></script>\n+<script src=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.1/js/all.min.js\" integrity=\"sha256-Z1Nvg/+y2+vRFhFgFij7Lv0r77yG3hOvWz2wI0SfTa0=\" crossorigin=\"anonymous\"></script>\n+<script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js\" integrity=\"sha256-U5ZEeKfGNOja007MMD3YBI0A3OSZOQbeG6z2f2Y0hu8=\" crossorigin=\"anonymous\"></script>\n+<script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js\" integrity=\"sha256-hYXbQJK4qdJiAeDVjjQ9G0D6A0xLnDQ4eJI9dkm7Fpk=\" crossorigin=\"anonymous\"></script>\n" } ]
Go
Apache License 2.0
google/gvisor
Fix d3-based performance graphs in Firefox. Reported by Thomas Gleixner in https://lore.kernel.org/lkml/87a68vtvhf.ffs@tglx/ PiperOrigin-RevId: 465692826
259,907
06.08.2022 19:58:54
25,200
0d7a1d07110f54a7f9740150d873f9bd28c2d43d
Lower layer files that can not be copied up are not writable. Make access(W_OK) return EACCES in overlayfs if file exists only on lower layer and can not be copied up. Earlier, access(W_OK) was succeeding but operations that cause copy-up (like open(WR_ONLY)) were failing. This is likely to confuse applications.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/overlay/copy_up.go", "new_path": "pkg/sentry/fsimpl/overlay/copy_up.go", "diff": "@@ -31,6 +31,18 @@ func (d *dentry) isCopiedUp() bool {\nreturn d.copiedUp.Load() != 0\n}\n+func (d *dentry) canBeCopiedUp() bool {\n+ ftype := d.mode.Load() & linux.S_IFMT\n+ switch ftype {\n+ case linux.S_IFREG, linux.S_IFDIR, linux.S_IFLNK, linux.S_IFBLK, linux.S_IFCHR:\n+ // Can be copied-up.\n+ return true\n+ default:\n+ // Can't be copied-up.\n+ return false\n+ }\n+}\n+\n// copyUpLocked ensures that d exists on the upper layer, i.e. d.upperVD.Ok().\n//\n// Preconditions: filesystem.renameMu must be locked.\n@@ -48,12 +60,7 @@ func (d *dentry) copyUpMaybeSyntheticMountpointLocked(ctx context.Context, forSy\n// credentials from context rather an take an explicit creds parameter.\nctx = auth.ContextWithCredentials(ctx, d.fs.creds)\n- ftype := d.mode.Load() & linux.S_IFMT\n- switch ftype {\n- case linux.S_IFREG, linux.S_IFDIR, linux.S_IFLNK, linux.S_IFBLK, linux.S_IFCHR:\n- // Can be copied-up.\n- default:\n- // Can't be copied-up.\n+ if !d.canBeCopiedUp() {\nreturn linuxerr.EPERM\n}\n@@ -92,6 +99,7 @@ func (d *dentry) copyUpMaybeSyntheticMountpointLocked(ctx context.Context, forSy\n}\n// Perform copy-up.\n+ ftype := d.mode.Load() & linux.S_IFMT\nnewpop := vfs.PathOperation{\nRoot: d.parent.upperVD,\nStart: d.parent.upperVD,\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/overlay/filesystem.go", "new_path": "pkg/sentry/fsimpl/overlay/filesystem.go", "diff": "@@ -585,9 +585,18 @@ func (fs *filesystem) AccessAt(ctx context.Context, rp *vfs.ResolvingPath, creds\nif err := d.checkPermissions(creds, ats); err != nil {\nreturn err\n}\n- if ats.MayWrite() && rp.Mount().ReadOnly() {\n+ if !ats.MayWrite() {\n+ // Not requesting write permission. Allow it.\n+ return nil\n+ }\n+ if rp.Mount().ReadOnly() {\nreturn linuxerr.EROFS\n}\n+ if !d.upperVD.Ok() && !d.canBeCopiedUp() {\n+ // A lower layer file that can not be copied up, can not be written to.\n+ // Error out here. Don't give the application false hopes.\n+ return linuxerr.EACCES\n+ }\nreturn nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Lower layer files that can not be copied up are not writable. Make access(W_OK) return EACCES in overlayfs if file exists only on lower layer and can not be copied up. Earlier, access(W_OK) was succeeding but operations that cause copy-up (like open(WR_ONLY)) were failing. This is likely to confuse applications. PiperOrigin-RevId: 465818314
259,982
08.08.2022 00:52:53
25,200
e003828a6bcce828f90f500e42af3923926b0b50
Add SignalContainer() to GvisorContainer for multi-containers. SignalContainer() sends control message to signal the container in multi-container mode.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/control/lifecycle.go", "new_path": "pkg/sentry/control/lifecycle.go", "diff": "@@ -290,6 +290,8 @@ func (l *Lifecycle) getInitContainerProcess(containerID string) (*kernel.ThreadG\ntype ContainerArgs struct {\n// ContainerID.\nContainerID string `json:\"containerID\"`\n+ Signo int32 `json:\"signo\"`\n+ SignalAll bool `json:\"signalAll\"`\n}\n// WaitContainer waits for the container to exit and returns the exit status.\n@@ -328,3 +330,32 @@ func (l *Lifecycle) IsContainerRunning(args *ContainerArgs, isRunning *bool) err\n*isRunning = true\nreturn nil\n}\n+\n+// SignalContainer signals the container in multi-container mode. It returns error if the\n+// container hasn't started or has exited.\n+func (l *Lifecycle) SignalContainer(args *ContainerArgs, _ *struct{}) error {\n+ tg, err := l.getInitContainerProcess(args.ContainerID)\n+ if err != nil {\n+ return err\n+ }\n+\n+ l.mu.Lock()\n+ c, ok := l.containerMap[args.ContainerID]\n+ if !ok || c.state != stateRunning {\n+ l.mu.Unlock()\n+ return fmt.Errorf(\"%v container not running\", args.ContainerID)\n+ }\n+ l.mu.Unlock()\n+\n+ // Signalling a single process is supported only for the init process.\n+ if !args.SignalAll {\n+ if tg == nil {\n+ return fmt.Errorf(\"no process exists in %v\", tg)\n+ }\n+ return l.Kernel.SendExternalSignalThreadGroup(tg, &linux.SignalInfo{Signo: args.Signo})\n+ }\n+\n+ l.Kernel.Pause()\n+ defer l.Kernel.Unpause()\n+ return l.Kernel.SendContainerSignal(args.ContainerID, &linux.SignalInfo{Signo: args.Signo})\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Add SignalContainer() to GvisorContainer for multi-containers. SignalContainer() sends control message to signal the container in multi-container mode. PiperOrigin-RevId: 465975679
259,975
08.08.2022 12:54:28
25,200
a963196f43de72f411291837d453ebf1b7801fb8
Support process_vm_read for same user only.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_usermem.go", "new_path": "pkg/sentry/kernel/task_usermem.go", "diff": "@@ -21,10 +21,13 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n\"gvisor.dev/gvisor/pkg/hostarch\"\n+ \"gvisor.dev/gvisor/pkg/marshal\"\n\"gvisor.dev/gvisor/pkg/sentry/mm\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n+const iovecLength = 16\n+\n// MAX_RW_COUNT is the maximum size in bytes of a single read or write.\n// Reads and writes that exceed this size may be silently truncated.\n// (Linux: include/linux/fs.h:MAX_RW_COUNT)\n@@ -122,28 +125,33 @@ func (t *Task) CopyInVector(addr hostarch.Addr, maxElemSize, maxTotalSize int) (\n}\n// CopyOutIovecs converts src to an array of struct iovecs and copies it to the\n-// memory mapped at addr.\n+// memory mapped at addr for Task.\n//\n// Preconditions: Same as usermem.IO.CopyOut, plus:\n// - The caller must be running on the task goroutine.\n// - t's AddressSpace must be active.\nfunc (t *Task) CopyOutIovecs(addr hostarch.Addr, src hostarch.AddrRangeSeq) error {\n+ return copyOutIovecs(t, t, addr, src)\n+}\n+\n+// copyOutIovecs converts src to an array of struct iovecs and copies it to the\n+// memory mapped at addr.\n+func copyOutIovecs(ctx marshal.CopyContext, t *Task, addr hostarch.Addr, src hostarch.AddrRangeSeq) error {\nswitch t.Arch().Width() {\ncase 8:\n- const itemLen = 16\n- if _, ok := addr.AddLength(uint64(src.NumRanges()) * itemLen); !ok {\n+ if _, ok := addr.AddLength(uint64(src.NumRanges()) * iovecLength); !ok {\nreturn linuxerr.EFAULT\n}\n- b := t.CopyScratchBuffer(itemLen)\n+ b := ctx.CopyScratchBuffer(iovecLength)\nfor ; !src.IsEmpty(); src = src.Tail() {\nar := src.Head()\nhostarch.ByteOrder.PutUint64(b[0:8], uint64(ar.Start))\nhostarch.ByteOrder.PutUint64(b[8:16], uint64(ar.Length()))\n- if _, err := t.CopyOutBytes(addr, b); err != nil {\n+ if _, err := ctx.CopyOutBytes(addr, b); err != nil {\nreturn err\n}\n- addr += itemLen\n+ addr += iovecLength\n}\ndefault:\n@@ -153,32 +161,60 @@ func (t *Task) CopyOutIovecs(addr hostarch.Addr, src hostarch.AddrRangeSeq) erro\nreturn nil\n}\n-// CopyInIovecs copies an array of numIovecs struct iovecs from the memory\n+// CopyInIovecs copies in IoVecs for Task.\n+//\n+// Preconditions: Same as usermem.IO.CopyIn, plus:\n+// * The caller must be running on the task goroutine.\n+// * t's AddressSpace must be active.\n+func (t *Task) CopyInIovecs(addr hostarch.Addr, numIovecs int) (hostarch.AddrRangeSeq, error) {\n+ // Special case to avoid allocating allocating a single hostaddr.AddrRange.\n+ if numIovecs == 1 {\n+ return copyInIovec(t, t, addr)\n+ }\n+ iovecs, err := copyInIovecs(t, t, addr, numIovecs)\n+ if err != nil {\n+ return hostarch.AddrRangeSeq{}, err\n+ }\n+ return hostarch.AddrRangeSeqFromSlice(iovecs), nil\n+}\n+\n+func copyInIovec(ctx marshal.CopyContext, t *Task, addr hostarch.Addr) (hostarch.AddrRangeSeq, error) {\n+ if err := checkArch(t); err != nil {\n+ return hostarch.AddrRangeSeq{}, err\n+ }\n+ b := ctx.CopyScratchBuffer(iovecLength)\n+ ar, err := makeIovec(ctx, t, addr, b)\n+ if err != nil {\n+ return hostarch.AddrRangeSeq{}, err\n+ }\n+ return hostarch.AddrRangeSeqOf(ar).TakeFirst(MAX_RW_COUNT), nil\n+}\n+\n+// copyInIovecs copies an array of numIovecs struct iovecs from the memory\n// mapped at addr, converts them to hostarch.AddrRanges, and returns them as a\n// hostarch.AddrRangeSeq.\n//\n-// CopyInIovecs shares the following properties with Linux's\n+// copyInIovecs shares the following properties with Linux's\n// lib/iov_iter.c:import_iovec() => fs/read_write.c:rw_copy_check_uvector():\n//\n// - If the length of any AddrRange would exceed the range of an ssize_t,\n-// CopyInIovecs returns EINVAL.\n+// copyInIovecs returns EINVAL.\n//\n// - If the length of any AddrRange would cause its end to overflow,\n-// CopyInIovecs returns EFAULT.\n+// copyInIovecs returns EFAULT.\n//\n// - If any AddrRange would include addresses outside the application address\n-// range, CopyInIovecs returns EFAULT.\n+// range, copyInIovecs returns EFAULT.\n//\n// - The combined length of all AddrRanges is limited to MAX_RW_COUNT. If the\n// combined length of all AddrRanges would otherwise exceed this amount, ranges\n// beyond MAX_RW_COUNT are silently truncated.\n-//\n-// Preconditions: Same as usermem.IO.CopyIn, plus:\n-// - The caller must be running on the task goroutine.\n-// - t's AddressSpace must be active.\n-func (t *Task) CopyInIovecs(addr hostarch.Addr, numIovecs int) (hostarch.AddrRangeSeq, error) {\n+func copyInIovecs(ctx marshal.CopyContext, t *Task, addr hostarch.Addr, numIovecs int) ([]hostarch.AddrRange, error) {\n+ if err := checkArch(t); err != nil {\n+ return nil, err\n+ }\nif numIovecs == 0 {\n- return hostarch.AddrRangeSeq{}, nil\n+ return nil, nil\n}\nvar dst []hostarch.AddrRange\n@@ -186,42 +222,20 @@ func (t *Task) CopyInIovecs(addr hostarch.Addr, numIovecs int) (hostarch.AddrRan\ndst = make([]hostarch.AddrRange, 0, numIovecs)\n}\n- switch t.Arch().Width() {\n- case 8:\n- const itemLen = 16\n- if _, ok := addr.AddLength(uint64(numIovecs) * itemLen); !ok {\n- return hostarch.AddrRangeSeq{}, linuxerr.EFAULT\n+ if _, ok := addr.AddLength(uint64(numIovecs) * iovecLength); !ok {\n+ return nil, linuxerr.EFAULT\n}\n- b := t.CopyScratchBuffer(itemLen)\n+ b := ctx.CopyScratchBuffer(iovecLength)\nfor i := 0; i < numIovecs; i++ {\n- if _, err := t.CopyInBytes(addr, b); err != nil {\n- return hostarch.AddrRangeSeq{}, err\n- }\n-\n- base := hostarch.Addr(hostarch.ByteOrder.Uint64(b[0:8]))\n- length := hostarch.ByteOrder.Uint64(b[8:16])\n- if length > math.MaxInt64 {\n- return hostarch.AddrRangeSeq{}, linuxerr.EINVAL\n- }\n- ar, ok := t.MemoryManager().CheckIORange(base, int64(length))\n- if !ok {\n- return hostarch.AddrRangeSeq{}, linuxerr.EFAULT\n- }\n-\n- if numIovecs == 1 {\n- // Special case to avoid allocating dst.\n- return hostarch.AddrRangeSeqOf(ar).TakeFirst(MAX_RW_COUNT), nil\n+ ar, err := makeIovec(ctx, t, addr, b)\n+ if err != nil {\n+ return []hostarch.AddrRange{}, err\n}\ndst = append(dst, ar)\n- addr += itemLen\n+ addr += iovecLength\n}\n-\n- default:\n- return hostarch.AddrRangeSeq{}, linuxerr.ENOSYS\n- }\n-\n// Truncate to MAX_RW_COUNT.\nvar total uint64\nfor i := range dst {\n@@ -233,7 +247,31 @@ func (t *Task) CopyInIovecs(addr hostarch.Addr, numIovecs int) (hostarch.AddrRan\ntotal += dstlen\n}\n- return hostarch.AddrRangeSeqFromSlice(dst), nil\n+ return dst, nil\n+}\n+\n+func checkArch(t *Task) error {\n+ if t.Arch().Width() != 8 {\n+ return linuxerr.ENOSYS\n+ }\n+ return nil\n+}\n+\n+func makeIovec(ctx marshal.CopyContext, t *Task, addr hostarch.Addr, b []byte) (hostarch.AddrRange, error) {\n+ if _, err := ctx.CopyInBytes(addr, b); err != nil {\n+ return hostarch.AddrRange{}, err\n+ }\n+\n+ base := hostarch.Addr(hostarch.ByteOrder.Uint64(b[0:8]))\n+ length := hostarch.ByteOrder.Uint64(b[8:16])\n+ if length > math.MaxInt64 {\n+ return hostarch.AddrRange{}, linuxerr.EINVAL\n+ }\n+ ar, ok := t.MemoryManager().CheckIORange(base, int64(length))\n+ if !ok {\n+ return hostarch.AddrRange{}, linuxerr.EFAULT\n+ }\n+ return ar, nil\n}\n// SingleIOSequence returns a usermem.IOSequence representing [addr,\n@@ -287,6 +325,7 @@ type taskCopyContext struct {\nctx context.Context\nt *Task\nopts usermem.IOOpts\n+ allocateNewBuffers bool\n}\n// CopyContext returns a marshal.CopyContext that copies to/from t's address\n@@ -301,7 +340,7 @@ func (t *Task) CopyContext(ctx context.Context, opts usermem.IOOpts) *taskCopyCo\n// CopyScratchBuffer implements marshal.CopyContext.CopyScratchBuffer.\nfunc (cc *taskCopyContext) CopyScratchBuffer(size int) []byte {\n- if ctxTask, ok := cc.ctx.(*Task); ok {\n+ if ctxTask, ok := cc.ctx.(*Task); ok && !cc.allocateNewBuffers {\nreturn ctxTask.CopyScratchBuffer(size)\n}\nreturn make([]byte, size)\n@@ -337,6 +376,17 @@ func (cc *taskCopyContext) CopyOutBytes(addr hostarch.Addr, src []byte) (int, er\nreturn tmm.CopyOut(cc.ctx, addr, src, cc.opts)\n}\n+// CopyOutIovecs converts src to an array of struct iovecs and copies it to the\n+// memory mapped at addr for Task.\n+func (cc *taskCopyContext) CopyOutIovecs(addr hostarch.Addr, src hostarch.AddrRangeSeq) error {\n+ return copyOutIovecs(cc, cc.t, addr, src)\n+}\n+\n+// CopyInIovecs copies in IoVecs for taskCopyContext.\n+func (cc *taskCopyContext) CopyInIovecs(addr hostarch.Addr, numIovecs int) ([]hostarch.AddrRange, error) {\n+ return copyInIovecs(cc, cc.t, addr, numIovecs)\n+}\n+\ntype ownTaskCopyContext struct {\nt *Task\nopts usermem.IOOpts\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/mmap.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/mmap.go", "diff": "@@ -22,6 +22,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/tmpfs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n)\n// Mmap implements Linux syscall mmap(2).\n@@ -102,3 +103,122 @@ func Mmap(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallC\nrv, err := t.MemoryManager().MMap(t, opts)\nreturn uintptr(rv), nil, err\n}\n+\n+// ProcessVMReadv implements process_vm_readv(2).\n+func ProcessVMReadv(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ return processVMRW(t, args, false /*isWrite*/)\n+}\n+\n+// ProcessVMWritev implements process_vm_writev(2).\n+func ProcessVMWritev(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ return processVMRW(t, args, true /*isWrite*/)\n+}\n+\n+func processVMRW(t *kernel.Task, args arch.SyscallArguments, isWrite bool) (uintptr, *kernel.SyscallControl, error) {\n+ pid := kernel.ThreadID(args[0].Int())\n+ lvec := hostarch.Addr(args[1].Pointer())\n+ liovcnt := int(args[2].Int64())\n+ rvec := hostarch.Addr(args[3].Pointer())\n+ riovcnt := int(args[4].Int64())\n+ flags := args[5].Int()\n+\n+ switch {\n+ case flags != 0:\n+ return 0, nil, linuxerr.EINVAL\n+ case liovcnt < 0 || liovcnt > linux.UIO_MAXIOV:\n+ return 0, nil, linuxerr.EINVAL\n+ case riovcnt < 0 || riovcnt > linux.UIO_MAXIOV:\n+ return 0, nil, linuxerr.EFAULT\n+ case lvec == 0 || rvec == 0:\n+ return 0, nil, linuxerr.EFAULT\n+ case riovcnt > linux.UIO_MAXIOV || liovcnt > linux.UIO_MAXIOV:\n+ return 0, nil, linuxerr.EINVAL\n+ case liovcnt == 0 || riovcnt == 0:\n+ return 0, nil, nil\n+ }\n+\n+ localProcess := t.ThreadGroup().Leader()\n+ if localProcess == nil {\n+ return 0, nil, linuxerr.ESRCH\n+ }\n+ remoteThreadGroup := localProcess.PIDNamespace().ThreadGroupWithID(pid)\n+ if remoteThreadGroup == nil {\n+ return 0, nil, linuxerr.ESRCH\n+ }\n+ remoteProcess := remoteThreadGroup.Leader()\n+\n+ // For the write case, we read from the local process and write to the remote process.\n+ if isWrite {\n+ return doProcessVMReadWrite(localProcess, remoteProcess, lvec, rvec, liovcnt, riovcnt)\n+ }\n+ // For the read case, we read from the remote process and write to the local process.\n+ return doProcessVMReadWrite(remoteProcess, localProcess, rvec, lvec, riovcnt, liovcnt)\n+}\n+\n+func doProcessVMReadWrite(rProcess, wProcess *kernel.Task, rAddr, wAddr hostarch.Addr, rIovecCount, wIovecCount int) (uintptr, *kernel.SyscallControl, error) {\n+ rCtx := rProcess.CopyContext(rProcess, usermem.IOOpts{})\n+ wCtx := wProcess.CopyContext(wProcess, usermem.IOOpts{})\n+\n+ rIovecs, err := rCtx.CopyInIovecs(rAddr, rIovecCount)\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+ wIovecs, err := wCtx.CopyInIovecs(wAddr, wIovecCount)\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+\n+ bufSize := 0\n+ for _, rIovec := range rIovecs {\n+ if int(rIovec.Length()) > bufSize {\n+ bufSize = int(rIovec.Length())\n+ }\n+ }\n+\n+ buf := rCtx.CopyScratchBuffer(bufSize)\n+ wCount := 0\n+ for _, rIovec := range rIovecs {\n+ if len(wIovecs) <= 0 {\n+ break\n+ }\n+\n+ buf = buf[0:int(rIovec.Length())]\n+ bytes, err := rCtx.CopyInBytes(rIovec.Start, buf)\n+ if linuxerr.Equals(linuxerr.EFAULT, err) {\n+ return uintptr(wCount), nil, nil\n+ }\n+ if err != nil {\n+ return uintptr(wCount), nil, err\n+ }\n+ if bytes != int(rIovec.Length()) {\n+ return uintptr(wCount), nil, nil\n+ }\n+ start := 0\n+ for bytes > start && 0 < len(wIovecs) {\n+ writeLength := int(wIovecs[0].Length())\n+ if writeLength > (bytes - start) {\n+ writeLength = bytes - start\n+ }\n+ out, err := wCtx.CopyOutBytes(wIovecs[0].Start, buf[start:writeLength+start])\n+ wCount += out\n+ start += out\n+ if linuxerr.Equals(linuxerr.EFAULT, err) {\n+ return uintptr(wCount), nil, nil\n+ }\n+ if err != nil {\n+ return uintptr(wCount), nil, err\n+ }\n+ if out != writeLength {\n+ return uintptr(wCount), nil, nil\n+ }\n+ wIovecs[0].Start += hostarch.Addr(out)\n+ if !wIovecs[0].WellFormed() {\n+ return uintptr(wCount), nil, err\n+ }\n+ if wIovecs[0].Length() == 0 {\n+ wIovecs = wIovecs[1:]\n+ }\n+ }\n+ }\n+ return uintptr(wCount), nil, nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/vfs2.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/vfs2.go", "diff": "@@ -156,6 +156,8 @@ func Override() {\ns.Table[299] = syscalls.Supported(\"recvmmsg\", RecvMMsg)\ns.Table[306] = syscalls.Supported(\"syncfs\", Syncfs)\ns.Table[307] = syscalls.Supported(\"sendmmsg\", SendMMsg)\n+ s.Table[310] = syscalls.Supported(\"process_vm_readv\", ProcessVMReadv)\n+ s.Table[311] = syscalls.Supported(\"process_vm_writev\", ProcessVMWritev)\ns.Table[316] = syscalls.Supported(\"renameat2\", Renameat2)\ns.Table[319] = syscalls.Supported(\"memfd_create\", MemfdCreate)\ns.Table[322] = syscalls.SupportedPoint(\"execveat\", Execveat, linux.PointExecveat)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -1063,3 +1063,8 @@ syscall_test(\nsize = \"small\",\ntest = \"//test/syscalls/linux:close_range_test\",\n)\n+\n+syscall_test(\n+ size = \"small\",\n+ test = \"//test/syscalls/linux:process_vm_read_write\",\n+)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -4474,3 +4474,20 @@ cc_binary(\n\"//test/util:thread_util\",\n],\n)\n+\n+cc_binary(\n+ name = \"process_vm_read_write\",\n+ testonly = 1,\n+ srcs = [\"process_vm_read_write.cc\"],\n+ linkstatic = 1,\n+ deps = [\n+ gtest,\n+ \"//test/util:capability_util\",\n+ \"//test/util:logging\",\n+ \"//test/util:multiprocess_util\",\n+ \"//test/util:posix_error\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ \"@com_google_absl//absl/strings\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/syscalls/linux/process_vm_read_write.cc", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <asm-generic/errno-base.h>\n+#include <bits/types/struct_iovec.h>\n+#include <errno.h>\n+#include <string.h>\n+#include <sys/types.h>\n+#include <sys/uio.h>\n+#include <sys/wait.h>\n+#include <unistd.h>\n+\n+#include <climits>\n+#include <csignal>\n+#include <cstddef>\n+#include <functional>\n+#include <iostream>\n+#include <memory>\n+#include <ostream>\n+#include <string>\n+#include <vector>\n+\n+#include \"gmock/gmock.h\"\n+#include \"gtest/gtest.h\"\n+#include \"absl/strings/str_cat.h\"\n+#include \"absl/strings/str_join.h\"\n+#include \"test/util/linux_capability_util.h\"\n+#include \"test/util/logging.h\"\n+#include \"test/util/multiprocess_util.h\"\n+#include \"test/util/posix_error.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class TestIovecs {\n+ public:\n+ TestIovecs(std::vector<std::string>& data) {\n+ data_ = std::vector<std::string>(data.size());\n+ initial_ = std::vector<std::string>(data.size());\n+ for (int i = 0; i < data.size(); ++i) {\n+ data_[i] = data[i];\n+ initial_[i] = data[i];\n+ struct iovec iov;\n+ iov.iov_len = data_[i].size();\n+ iov.iov_base = data_[i].data();\n+ iovecs_.push_back(iov);\n+ bytes_ += data[i].size();\n+ }\n+ }\n+\n+ bool compare(std::vector<std::string> other) {\n+ auto want = absl::StrJoin(other, \"\");\n+ auto got = absl::StrJoin(data_, \"\");\n+ // If the other buffer is smaller than this, make sure the remaining bytes\n+ // haven't been overwritten.\n+ if (want.size() < got.size()) {\n+ auto initial = absl::StrJoin(initial_, \"\");\n+ want = absl::StrCat(want, initial.substr(want.size()));\n+ }\n+ // If the other buffer is smaller, truncate it so we can compare the two.\n+ if (want.size() > got.size()) {\n+ want = want.substr(0, got.size());\n+ }\n+ if (want != got) {\n+ std::cerr << \"Mismatch buffers:\\n want: \" << want << \"\\n got: \" << got\n+ << std::endl;\n+ return false;\n+ }\n+\n+ return true;\n+ }\n+\n+ std::vector<struct iovec*> marshal() {\n+ std::vector<struct iovec*> ret(iovecs_.size());\n+ for (int i = 0; i < iovecs_.size(); ++i) {\n+ ret[i] = &iovecs_[i];\n+ }\n+ return ret;\n+ }\n+\n+ ssize_t total_bytes() { return bytes_; }\n+\n+ private:\n+ ssize_t bytes_ = 0;\n+ std::vector<std::string> data_;\n+ std::vector<std::string> initial_;\n+ std::vector<struct iovec> iovecs_;\n+};\n+\n+struct ProcessVMTestCase {\n+ std::string test_name;\n+ std::vector<std::string> local_data;\n+ std::vector<std::string> remote_data;\n+};\n+\n+using ProcessVMTest = ::testing::TestWithParam<ProcessVMTestCase>;\n+\n+bool ProcessVMCallsNotSupported() {\n+ struct iovec iov;\n+ // Flags should be 0.\n+ ssize_t ret = process_vm_readv(0, &iov, 1, &iov, 1, 10);\n+ if (ret != 0 && errno == ENOSYS) return true;\n+\n+ ret = process_vm_writev(0, &iov, 1, &iov, 1, 10);\n+ return ret != 0 && errno == ENOSYS;\n+}\n+\n+// TestReadvSameProcess calls process_vm_readv in the same process with\n+// various local/remote buffers.\n+TEST_P(ProcessVMTest, TestReadvSameProcess) {\n+ SKIP_IF(ProcessVMCallsNotSupported());\n+ auto local_data = GetParam().local_data;\n+ auto remote_data = GetParam().remote_data;\n+ TestIovecs local_iovecs(local_data);\n+ TestIovecs remote_iovecs(remote_data);\n+\n+ auto local = local_iovecs.marshal();\n+ auto remote = remote_iovecs.marshal();\n+ auto expected_bytes =\n+ std::min(remote_iovecs.total_bytes(), local_iovecs.total_bytes());\n+ EXPECT_THAT(process_vm_readv(getpid(), *(local.data()), local.size(),\n+ *(remote.data()), remote.size(), 0),\n+ SyscallSucceedsWithValue(expected_bytes));\n+ EXPECT_TRUE(local_iovecs.compare(remote_data));\n+}\n+\n+// TestReadvSubProcess repeats the previous test in a forked process.\n+TEST_P(ProcessVMTest, TestReadvSubProcess) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE((HaveCapability(CAP_SYS_PTRACE))));\n+ SKIP_IF(ProcessVMCallsNotSupported());\n+ auto local_data = GetParam().local_data;\n+ auto remote_data = GetParam().remote_data;\n+\n+ TestIovecs remote_iovecs(remote_data);\n+ auto remote = remote_iovecs.marshal();\n+ auto remote_ptr = remote[0];\n+ auto remote_size = remote.size();\n+ auto remote_total_bytes = remote_iovecs.total_bytes();\n+\n+ const std::function<void()> fn = [local_data, remote_data, remote_ptr,\n+ remote_size, remote_total_bytes] {\n+ std::vector<std::string> local_fn_data = local_data;\n+ TestIovecs local_iovecs(local_fn_data);\n+ auto local = local_iovecs.marshal();\n+ int ret = process_vm_readv(getppid(), local[0], local.size(), remote_ptr,\n+ remote_size, 0);\n+ auto expected_bytes =\n+ std::min(remote_total_bytes, local_iovecs.total_bytes());\n+ TEST_CHECK_MSG(\n+ ret == expected_bytes,\n+ absl::StrCat(\"want: \", expected_bytes, \" got: \", ret).c_str());\n+ TEST_CHECK(local_iovecs.compare(remote_data));\n+ };\n+ EXPECT_THAT(InForkedProcess(fn), IsPosixErrorOkAndHolds(0));\n+}\n+\n+// TestWritevSameProcess calls process_vm_writev in the same process with\n+// various local/remote buffers.\n+TEST_P(ProcessVMTest, TestWritevSameProcess) {\n+ SKIP_IF(ProcessVMCallsNotSupported());\n+ auto local_data = GetParam().local_data;\n+ auto remote_data = GetParam().remote_data;\n+\n+ TestIovecs local_iovecs(local_data);\n+ TestIovecs remote_iovecs(remote_data);\n+\n+ auto local = local_iovecs.marshal();\n+ auto remote = remote_iovecs.marshal();\n+ auto expected_bytes =\n+ std::min(remote_iovecs.total_bytes(), local_iovecs.total_bytes());\n+ EXPECT_THAT(process_vm_writev(getpid(), remote[0], remote.size(), local[0],\n+ local.size(), 0),\n+ SyscallSucceedsWithValue(expected_bytes));\n+ EXPECT_TRUE(local_iovecs.compare(remote_data));\n+}\n+\n+// TestWritevSubProcess repeats the previous test in a forked process.\n+TEST_P(ProcessVMTest, TestWritevSubProcess) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE((HaveCapability(CAP_SYS_PTRACE))));\n+ SKIP_IF(ProcessVMCallsNotSupported());\n+ auto local_data = GetParam().local_data;\n+ auto remote_data = GetParam().remote_data;\n+ TestIovecs remote_iovecs(remote_data);\n+ auto remote = remote_iovecs.marshal();\n+ auto remote_ptr = remote[0];\n+ auto remote_size = remote.size();\n+ auto remote_total_bytes = remote_iovecs.total_bytes();\n+\n+ const std::function<void()> fn = [local_data, remote_ptr, remote_size,\n+ remote_total_bytes] {\n+ std::vector<std::string> local_fn_data = local_data;\n+ TestIovecs local_iovecs(local_fn_data);\n+ auto local = local_iovecs.marshal();\n+ int ret = process_vm_writev(getppid(), local[0], local.size(), remote_ptr,\n+ remote_size, 0);\n+ auto expected_bytes =\n+ std::min(remote_total_bytes, local_iovecs.total_bytes());\n+ TEST_CHECK_MSG(\n+ ret == expected_bytes,\n+ absl::StrCat(\"want: \", expected_bytes, \" got: \", ret).c_str());\n+ };\n+\n+ EXPECT_THAT(InForkedProcess(fn), IsPosixErrorOkAndHolds(0));\n+ EXPECT_TRUE(remote_iovecs.compare(local_data));\n+}\n+\n+INSTANTIATE_TEST_SUITE_P(\n+ ProcessVMTests, ProcessVMTest,\n+ ::testing::ValuesIn<ProcessVMTestCase>(\n+ {{\"BothEmpty\" /*test name*/,\n+ {\"\"} /*local buffer*/,\n+ {\"\"} /*remote buffer*/},\n+ {\"EmptyLocal\", {\"\"}, {\"All too easy.\"}},\n+ {\"EmptyRemote\", {\"Impressive. Most impressive.\"}, {\"\"}},\n+ {\"SingleChar\", {\"l\"}, {\"r\"}},\n+ {\"LargerRemoteBuffer\",\n+ {\"OK, I'll try\"},\n+ {\"No!\", \"Try not\", \"Do...or do not\", \"There is no try.\"}},\n+ {\"LargerLocalBuffer\",\n+ {\"Look!\", \"The cave is collapsing!\"},\n+ {\"This is no cave.\"}},\n+ {\"BothWithMultipleIovecs\",\n+ {\"Obi-wan never told you what happened to your father.\",\n+ \"He told me enough...he told me you killed him.\"},\n+ {\"No...I am your father.\", \"No. No.\", \"That's not true.\",\n+ \"That's impossible!\"}}}),\n+ [](const ::testing::TestParamInfo<ProcessVMTest::ParamType>& info) {\n+ return info.param.test_name;\n+ });\n+\n+TEST(ProcessVMInvalidTest, NonZeroFlags) {\n+ SKIP_IF(ProcessVMCallsNotSupported());\n+ struct iovec iov;\n+ // Flags should be 0.\n+ EXPECT_THAT(process_vm_readv(0, &iov, 1, &iov, 1, 10),\n+ SyscallFailsWithErrno(EINVAL));\n+ EXPECT_THAT(process_vm_writev(0, &iov, 1, &iov, 1, 10),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+TEST(ProcessVMInvalidTest, NullLocalIovec) {\n+ SKIP_IF(ProcessVMCallsNotSupported());\n+ struct iovec iov;\n+ pid_t child = fork();\n+ if (child == 0) {\n+ while (true) {\n+ sleep(1);\n+ }\n+ }\n+\n+ EXPECT_THAT(process_vm_readv(child, nullptr, 1, &iov, 1, 0),\n+ SyscallFailsWithErrno(EFAULT));\n+\n+ EXPECT_THAT(process_vm_writev(child, nullptr, 1, &iov, 1, 0),\n+ SyscallFailsWithErrno(EFAULT));\n+ EXPECT_THAT(kill(child, SIGKILL), SyscallSucceeds());\n+ EXPECT_THAT(waitpid(child, 0, 0), SyscallSucceeds());\n+}\n+\n+TEST(ProcessVMInvalidTest, NULLRemoteIovec) {\n+ SKIP_IF(ProcessVMCallsNotSupported());\n+ const std::function<void()> fn = [] {\n+ std::string contents = \"3263827\";\n+ struct iovec child_iov;\n+ child_iov.iov_base = contents.data();\n+ child_iov.iov_len = contents.size();\n+\n+ pid_t parent = getppid();\n+ int ret =\n+ process_vm_readv(parent, &child_iov, contents.length(), nullptr, 1, 0);\n+ TEST_CHECK(errno == EFAULT || errno == EINVAL);\n+\n+ ret =\n+ process_vm_writev(parent, &child_iov, contents.length(), nullptr, 1, 0);\n+ TEST_CHECK(errno == EFAULT || errno == EINVAL);\n+ };\n+ ASSERT_THAT(InForkedProcess(fn), IsPosixErrorOkAndHolds(0));\n+}\n+\n+TEST(ProcessVMInvalidTest, ProcessNoExist) {\n+ SKIP_IF(ProcessVMCallsNotSupported());\n+ struct iovec iov;\n+ EXPECT_THAT(process_vm_readv(-1, &iov, 1, &iov, 1, 0),\n+ SyscallFailsWithErrno(::testing::AnyOf(ESRCH, EFAULT)));\n+ EXPECT_THAT(process_vm_writev(-1, &iov, 1, &iov, 1, 0),\n+ SyscallFailsWithErrno(::testing::AnyOf(ESRCH, EFAULT)));\n+}\n+\n+TEST(ProcessVMInvalidTest, InvalidLength) {\n+ SKIP_IF(ProcessVMCallsNotSupported());\n+ std::string contents = \"3263827\";\n+ struct iovec iov;\n+ iov.iov_base = contents.data();\n+ auto iov_addr = &iov;\n+ const std::function<void()> fn = [=] {\n+ struct iovec child_iov;\n+ std::string contents = \"3263827\";\n+ child_iov.iov_base = contents.data();\n+ child_iov.iov_len = contents.size();\n+\n+ pid_t parent = getppid();\n+ TEST_CHECK_ERRNO(process_vm_readv(parent, &child_iov, contents.length(),\n+ iov_addr, -1, 0),\n+ EFAULT);\n+ TEST_CHECK_ERRNO(process_vm_writev(parent, &child_iov, contents.length(),\n+ iov_addr, -1, 0),\n+ EFAULT);\n+\n+ TEST_CHECK_ERRNO(process_vm_readv(parent, &child_iov, -1, iov_addr,\n+ contents.length(), 0),\n+ EINVAL);\n+\n+ TEST_CHECK_ERRNO(process_vm_writev(parent, &child_iov, -1, iov_addr,\n+ contents.length(), 0),\n+ EINVAL);\n+ TEST_CHECK_ERRNO(process_vm_readv(parent, &child_iov, contents.length(),\n+ iov_addr, IOV_MAX + 1, 0),\n+ EFAULT);\n+\n+ TEST_CHECK_ERRNO(process_vm_writev(parent, &child_iov, contents.length(),\n+ iov_addr, IOV_MAX + 1, 0),\n+ EFAULT);\n+\n+ TEST_CHECK_ERRNO(process_vm_readv(parent, &child_iov, IOV_MAX + 2, iov_addr,\n+ contents.length(), 0),\n+ EINVAL);\n+\n+ TEST_CHECK_ERRNO(process_vm_writev(parent, &child_iov, IOV_MAX + 8,\n+ iov_addr, contents.length(), 0),\n+ EINVAL);\n+ };\n+ EXPECT_THAT(InForkedProcess(fn), IsPosixErrorOkAndHolds(0));\n+}\n+\n+TEST(ProcessVMInvalidTest, PartialReadWrite) {\n+ SKIP_IF(ProcessVMCallsNotSupported());\n+ std::string iov_content_1 = \"1138\";\n+ std::string iov_content_2 = \"3720\";\n+ struct iovec iov[2];\n+ iov[0].iov_base = iov_content_1.data();\n+ iov[0].iov_len = iov_content_1.size();\n+ iov[1].iov_base = iov_content_2.data();\n+ iov[1].iov_len = iov_content_2.size();\n+\n+ std::string iov_corrupted_content_1 = iov_content_1;\n+ struct iovec corrupted_iov[2];\n+ corrupted_iov[0].iov_base = iov_corrupted_content_1.data();\n+ corrupted_iov[0].iov_len = iov_corrupted_content_1.size();\n+ corrupted_iov[1].iov_base = (void*)0xDEADBEEF;\n+ corrupted_iov[1].iov_len = 42;\n+\n+ EXPECT_THAT(\n+ RetryEINTR(process_vm_writev)(getpid(), iov, 2, corrupted_iov, 2, 0),\n+ SyscallSucceedsWithValue(iov_content_1.size()));\n+ EXPECT_THAT(\n+ RetryEINTR(process_vm_readv)(getpid(), corrupted_iov, 2, iov, 2, 0),\n+ SyscallSucceedsWithValue(iov_content_1.size()));\n+ EXPECT_THAT(\n+ RetryEINTR(process_vm_writev)(getpid(), corrupted_iov, 2, iov, 2, 0),\n+ SyscallSucceedsWithValue(iov_content_1.size()));\n+ EXPECT_THAT(\n+ RetryEINTR(process_vm_readv)(getpid(), iov, 2, corrupted_iov, 2, 0),\n+ SyscallSucceedsWithValue(iov_content_1.size()));\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Support process_vm_read for same user only. PiperOrigin-RevId: 466123035
259,853
10.08.2022 11:42:17
25,200
778db1d8bc5b8e967bd18133462fb78a48756305
Deflake 32bit_test_linux
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/32bit.cc", "new_path": "test/syscalls/linux/32bit.cc", "diff": "@@ -131,6 +131,20 @@ TEST(Syscall32Bit, Sysenter) {\n}\n}\n+class KilledByOneOfSignals {\n+ public:\n+ KilledByOneOfSignals(int signum1, int signum2)\n+ : signum1_(signum1), signum2_(signum2) {}\n+ bool operator()(int exit_status) const {\n+ if (!WIFSIGNALED(exit_status)) return false;\n+ int sig = WTERMSIG(exit_status);\n+ return sig == signum1_ || sig == signum2_;\n+ }\n+\n+ private:\n+ const int signum1_, signum2_;\n+};\n+\nTEST(Syscall32Bit, Syscall) {\nif ((PlatformSupport32Bit() == PlatformSupport::Allowed ||\nPlatformSupport32Bit() == PlatformSupport::Ignored) &&\n@@ -151,9 +165,11 @@ TEST(Syscall32Bit, Syscall) {\nbreak;\ncase PlatformSupport::Ignored:\n- // See above.\n+ // FIXME(b/241819530): SIGSEGV was returned due to a kernel bug that has\n+ // been fixed recently. Let's continue accept SIGSEGV while bad kernels\n+ // are running in prod.\nEXPECT_EXIT(ExitGroup32(kSyscall, kExitCode),\n- ::testing::KilledBySignal(SIGSEGV), \"\");\n+ KilledByOneOfSignals(SIGTRAP, SIGSEGV), \"\");\nbreak;\ncase PlatformSupport::Allowed:\n" } ]
Go
Apache License 2.0
google/gvisor
Deflake 32bit_test_linux PiperOrigin-RevId: 466747499
260,009
10.08.2022 13:23:19
25,200
a4fb3b200fdc05ac14aedcfc3d5b1b0c89a8a372
Fix panic on nil map in Fragmentation. A rare bug occurs when assigning a value to the reassemblers map causes a panic due to the map being nil. The only way this is possible is if Fragmentation.Release() is called before Process() is able to finish.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/internal/fragmentation/fragmentation.go", "new_path": "pkg/tcpip/network/internal/fragmentation/fragmentation.go", "diff": "@@ -175,6 +175,10 @@ func (f *Fragmentation) Process(\n}\nf.mu.Lock()\n+ if f.reassemblers == nil {\n+ return nil, 0, false, fmt.Errorf(\"Release() called before fragmentation processing could finish\")\n+ }\n+\nr, ok := f.reassemblers[id]\nif !ok {\nr = newReassembler(id, f.clock)\n" } ]
Go
Apache License 2.0
google/gvisor
Fix panic on nil map in Fragmentation. A rare bug occurs when assigning a value to the reassemblers map causes a panic due to the map being nil. The only way this is possible is if Fragmentation.Release() is called before Process() is able to finish. PiperOrigin-RevId: 466771159
259,891
10.08.2022 14:01:04
25,200
fefc03e1514f8de5f638d26bb7d3bce0d9a5fcb1
conntrack: remove unnecessary mutex tuple.mu protects only tupleID, which is only ever set at initialization.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/conntrack.go", "new_path": "pkg/tcpip/stack/conntrack.go", "diff": "@@ -60,17 +60,10 @@ type tuple struct {\n// packet seen on the connection.\nreply bool\n- mu sync.RWMutex `state:\"nosave\"`\n- // +checklocks:mu\n+ // tupleID is set at initialization and is immutable.\ntupleID tupleID\n}\n-func (t *tuple) id() tupleID {\n- t.mu.RLock()\n- defer t.mu.RUnlock()\n- return t.tupleID\n-}\n-\n// tupleID uniquely identifies a trackable connection in one direction.\n//\n// +stateify savable\n@@ -328,7 +321,7 @@ func getHeaders(pkt *PacketBuffer) (netHdr header.Network, transHdr header.Trans\npanic(\"should have dropped packets with IPv4 options\")\n}\n- if netHdr, transHdr, ok := getEmbeddedNetAndTransHeaders(pkt, header.IPv4MinimumSize, v4NetAndTransHdr, pkt.tuple.id().transProto); ok {\n+ if netHdr, transHdr, ok := getEmbeddedNetAndTransHeaders(pkt, header.IPv4MinimumSize, v4NetAndTransHdr, pkt.tuple.tupleID.transProto); ok {\nreturn netHdr, transHdr, true, true\n}\nreturn nil, nil, false, false\n@@ -355,7 +348,7 @@ func getHeaders(pkt *PacketBuffer) (netHdr header.Network, transHdr header.Trans\n// in the IPv6 packet should be a tracked protocol if we reach this point.\n//\n// TODO(https://gvisor.dev/issue/6789): Support extension headers.\n- transProto := pkt.tuple.id().transProto\n+ transProto := pkt.tuple.tupleID.transProto\nif got := header.IPv6(h).TransportProtocol(); got != transProto {\npanic(fmt.Sprintf(\"got TransportProtocol() = %d, want = %d\", got, transProto))\n}\n@@ -628,7 +621,7 @@ func (bkt *bucket) connForTID(tid tupleID, now tcpip.MonotonicTime) *tuple {\n// +checklocksread:bkt.mu\nfunc (bkt *bucket) connForTIDRLocked(tid tupleID, now tcpip.MonotonicTime) *tuple {\nfor other := bkt.tuples.Front(); other != nil; other = other.Next() {\n- if tid == other.id() && !other.conn.timedOut(now) {\n+ if tid == other.tupleID && !other.conn.timedOut(now) {\nreturn other\n}\n}\n@@ -641,7 +634,7 @@ func (ct *ConnTrack) finalize(cn *conn) finalizeResult {\nct.mu.RUnlock()\n{\n- tid := cn.reply.id()\n+ tid := cn.reply.tupleID\nid := ct.bucket(tid)\nbkt := &buckets[id]\n@@ -669,7 +662,7 @@ func (ct *ConnTrack) finalize(cn *conn) finalizeResult {\n// TODO(https://gvisor.dev/issue/6850): Investigate handling this clash\n// better.\n- tid := cn.original.id()\n+ tid := cn.original.tupleID\nid := ct.bucket(tid)\nbkt := &buckets[id]\nbkt.mu.Lock()\n@@ -756,9 +749,6 @@ func (cn *conn) performNAT(pkt *PacketBuffer, hook Hook, r *Route, portsOrIdents\ncn.mu.Lock()\ndefer cn.mu.Unlock()\n- cn.reply.mu.Lock()\n- defer cn.reply.mu.Unlock()\n-\nvar manip *manipType\nvar address *tcpip.Address\nvar portOrIdent *uint16\n@@ -892,7 +882,7 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, rt *Route) bool {\ndefer cn.mu.RUnlock()\nif reply {\n- tid := cn.original.id()\n+ tid := cn.original.tupleID\nif dnat {\nreturn tid, cn.sourceManip\n@@ -900,7 +890,7 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, rt *Route) bool {\nreturn tid, cn.destinationManip\n}\n- tid := cn.reply.id()\n+ tid := cn.reply.tupleID\nif dnat {\nreturn tid, cn.destinationManip\n}\n@@ -1086,7 +1076,7 @@ func (ct *ConnTrack) reapTupleLocked(reapingTuple *tuple, bktID int, bkt *bucket\notherTuple = &reapingTuple.conn.reply\n}\n- otherTupleBktID := ct.bucket(otherTuple.id())\n+ otherTupleBktID := ct.bucket(otherTuple.tupleID)\nreplyTupleInserted := reapingTuple.conn.getFinalizeResult() == finalizeResultSuccess\n// To maintain lock order, we can only reap both tuples if the tuple for the\n@@ -1140,6 +1130,6 @@ func (ct *ConnTrack) originalDst(epID TransportEndpointID, netProto tcpip.Networ\nreturn \"\", 0, &tcpip.ErrInvalidOptionValue{}\n}\n- id := t.conn.original.id()\n+ id := t.conn.original.tupleID\nreturn id.dstAddr, id.dstPortOrEchoReplyIdent, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/iptables_test.go", "new_path": "pkg/tcpip/stack/iptables_test.go", "diff": "@@ -225,7 +225,7 @@ func TestNATedConnectionReap(t *testing.T) {\nbkt.mu.RLock()\ndefer bkt.mu.RUnlock()\nfor tuple := bkt.tuples.Front(); tuple != nil; tuple = tuple.Next() {\n- if tuple.id() == tid {\n+ if tuple.tupleID == tid {\nt.Errorf(\"unexpectedly found tuple with ID = %#v; reply = %t\", tid, reply)\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
conntrack: remove unnecessary mutex tuple.mu protects only tupleID, which is only ever set at initialization. PiperOrigin-RevId: 466779629
260,009
10.08.2022 14:28:57
25,200
1faac756ee6daff574c3e371e503c14385ee4dd8
Add shim support for calling runsc create with --panic-log. Making the panic log directory be inside of the normal user-log directory makes it possible to simply reuse the same spec annotation.
[ { "change_type": "MODIFY", "old_path": "pkg/shim/proc/init.go", "new_path": "pkg/shim/proc/init.go", "diff": "@@ -73,6 +73,7 @@ type Init struct {\nIoGID int\nSandbox bool\nUserLog string\n+ PanicLog string\nMonitor ProcessMonitor\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/shim/runsc/runsc.go", "new_path": "pkg/shim/runsc/runsc.go", "diff": "@@ -108,6 +108,10 @@ type CreateOpts struct {\n// UserLog is a path to where runsc user log should be generated.\nUserLog string\n+\n+ // PanicLog is a path to where runsc will output its panic message\n+ // (in case it does panic).\n+ PanicLog string\n}\nfunc (o *CreateOpts) args() (out []string, err error) {\n@@ -124,6 +128,9 @@ func (o *CreateOpts) args() (out []string, err error) {\nif o.UserLog != \"\" {\nout = append(out, \"--user-log\", o.UserLog)\n}\n+ if o.PanicLog != \"\" {\n+ out = append(out, \"--panic-log\", o.PanicLog)\n+ }\nreturn out, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/shim/service.go", "new_path": "pkg/shim/service.go", "diff": "@@ -1097,6 +1097,7 @@ func newInit(path, workDir, namespace string, platform stdio.Platform, r *proc.C\np.IoGID = int(options.IoGID)\np.Sandbox = specutils.SpecContainerType(spec) == specutils.ContainerTypeSandbox\np.UserLog = utils.UserLogPath(spec)\n+ p.PanicLog = utils.PanicLogPath(spec)\np.Monitor = reaper.Default\nreturn p, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/shim/utils/utils.go", "new_path": "pkg/shim/utils/utils.go", "diff": "@@ -61,3 +61,12 @@ func UserLogPath(spec *specs.Spec) string {\n}\nreturn filepath.Join(sandboxLogDir, \"gvisor.log\")\n}\n+\n+// PanicLogPath gets the panic log path from OCI annotation.\n+func PanicLogPath(spec *specs.Spec) string {\n+ sandboxLogDir := spec.Annotations[sandboxLogDirAnnotation]\n+ if sandboxLogDir == \"\" {\n+ return \"\"\n+ }\n+ return filepath.Join(sandboxLogDir, \"gvisor_panic.log\")\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Add shim support for calling runsc create with --panic-log. Making the panic log directory be inside of the normal user-log directory makes it possible to simply reuse the same spec annotation. PiperOrigin-RevId: 466785655
259,992
11.08.2022 10:09:55
25,200
5852220509c8c27324a7006b45c9835c7ba814fa
Add tutorial for using Falco with gVisor
[ { "change_type": "MODIFY", "old_path": "g3doc/user_guide/tutorials/BUILD", "new_path": "g3doc/user_guide/tutorials/BUILD", "diff": "@@ -36,6 +36,15 @@ doc(\nweight = \"30\",\n)\n+doc(\n+ name = \"falco\",\n+ src = \"falco.md\",\n+ category = \"User Guide\",\n+ permalink = \"/docs/tutorials/falco/\",\n+ subcategory = \"Tutorials\",\n+ weight = \"35\",\n+)\n+\ndoc(\nname = \"knative\",\nsrc = \"knative.md\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "g3doc/user_guide/tutorials/falco.md", "diff": "+# Configuring Falco with gVisor\n+\n+[TOC]\n+\n+## Installation\n+\n+First, install [gVisor](/docs/user_guide/install/) and\n+[Falco](https://falco.org/docs/getting-started/installation/) on the machine.\n+Run `runsc --version` and check that `runsc version release-20220704.0` or newer\n+is reported. Run `falco --version` and check that `Falco version` reports\n+`0.32.1` or higher.\n+\n+Once both are installed, you can configure gVisor to connect to Falco whenever a\n+new sandbox is started. The first command below generates a configuration file\n+containing a list of trace points that Falco is interested in receiving. This\n+file is passed to gVisor during container startup so that gVisor connects to\n+Falco *before* the application starts. The second command installs runsc as a\n+Docker runtime pointing it to the configuration file we just generated:\n+\n+```shell\n+falco --gvisor-generate-config | sudo tee /etc/falco/pod-init.json\n+# Edit /etc/falco/pod-init.json, see note below.\n+sudo runsc install --runtime=runsc-falco -- --pod-init-config=/etc/falco/pod-init.json\n+sudo systemctl restart docker\n+```\n+\n+> **Note:** Between steps 1 and 2 above, edit the `pod-init.json` file to add\n+> `ignore_setup_error` to the sink options (this will be fixed in the next Falco\n+> release). The file will look like this:\n+\n+```json\n+ \"sinks\" : [\n+ {\n+ \"config\" : {\n+ \"endpoint\" : \"/tmp/gvisor.sock\"\n+ },\n+ \"name\" : \"remote\",\n+ \"ignore_setup_error\": true <== ADD THIS LINE\n+ }\n+ ]\n+```\n+\n+gVisor is now configured. Next, let's start Falco and tell it to enable gVisor\n+monitoring. You should use the same command line that you normally use to start\n+Falco with these additional flags:\n+\n+- `--gvisor-config`: path to the gVisor configuration file, in our case\n+ `/etc/falco/pod-init.json`.\n+- `--gvisor-root`: path to the `--root` flag that docker uses with gVisor,\n+ normally: `/var/run/docker/runtime-runc/moby`.\n+\n+For our example, let's just start with the default settings and rules:\n+\n+```shell\n+sudo falco \\\n+ -c /etc/falco/falco.yaml \\\n+ --gvisor-config /etc/falco/pod-init.json \\\n+ --gvisor-root /var/run/docker/runtime-runc/moby\n+```\n+\n+> **Note:** If you get `Error: Cannot find runsc binary`, make sure `runsc` is\n+> in the `PATH`.\n+\n+From this point on, every time a gVisor sandbox starts, it connects to Falco to\n+send trace points occurring inside the container. Those are translated into\n+Falco events that are processed by the rules you have defined. If you used the\n+command above, the configuration files are defined in\n+`/etc/falco/faco_rules.yaml` and `/etc/falco/faco_rules.local.yaml` (where you\n+can add your own rules).\n+\n+## Triggering Falco Events\n+\n+Let's run something interesting inside a container to see a few rules trigger in\n+Falco. Package managers, like `apt`, don't normally run inside containers in\n+production, and often indicate that an attacker is trying to install tools to\n+expose the container. To detect such cases, the default set of rules trigger an\n+`Error` event when the package manager is invoked. Let's see it in action, first\n+start a container and run a simple `apt` command:\n+\n+```shell\n+sudo docker run --rm --runtime=runsc-falco -ti ubuntu\n+$ apt update\n+```\n+\n+In the terminal where falco is running, you should see in the output many `Error\n+Package management process launched` events. Here is one of the events informing\n+that a package manager was invoked inside the container:\n+\n+```json\n+{\n+ \"output\": \"18:39:27.542112944: Error Package management process launched in container (user=root user_loginuid=0 command=apt apt update container_id=1473cfd51410 container_name=sad_wu image=ubuntu:latest) container=1473cfd51410 pid=4 tid=4\",\n+ \"priority\": \"Error\",\n+ \"rule\": \"Launch Package Management Process in Container\",\n+ \"source\": \"syscall\",\n+ \"tags\": [\n+ \"mitre_persistence\",\n+ \"process\"\n+ ],\n+ \"time\": \"2022-08-02T18:39:27.542112944Z\",\n+ \"output_fields\": {\n+ \"container.id\": \"1473cfd51410\",\n+ \"container.image.repository\": \"ubuntu\",\n+ \"container.image.tag\": \"latest\",\n+ \"container.name\": \"sad_wu\",\n+ \"evt.time\": 1659465567542113000,\n+ \"proc.cmdline\": \"apt apt update\",\n+ \"proc.vpid\": 4,\n+ \"thread.vtid\": 4,\n+ \"user.loginuid\": 0,\n+ \"user.name\": \"root\"\n+ }\n+}\n+```\n+\n+As you can see, it's warning that `apt update` command was ran inside container\n+`sad_wu`, and gives more information about the user, TID, image name, etc. There\n+are also rules that trigger when there is a write under `/` and other system\n+directories that are normally part of the image and shouldn't be changed. If we\n+proceed with installing packages into the container, apart from the event above,\n+there are a few other events that are triggered. Let's execute `apt-get install\n+-y netcat` and look at the output:\n+\n+```json\n+{\n+ \"output\": \"18:40:42.192811725: Warning Sensitive file opened for reading by non-trusted program (user=root user_loginuid=0 program=dpkg-preconfigure command=dpkg-preconfigure /usr/sbin/dpkg-preconfigure --apt file=/etc/shadow parent=sh gparent=<NA> ggparent=<NA> gggparent=<NA> container_id=1473cfd51410 image=ubuntu) container=1473cfd51410 pid=213 tid=213\",\n+ \"priority\": \"Warning\",\n+ \"rule\": \"Read sensitive file untrusted\",\n+ \"source\": \"syscall\",\n+ \"tags\": [\n+ \"filesystem\",\n+ \"mitre_credential_access\",\n+ \"mitre_discovery\"\n+ ],\n+}\n+\n+{\n+ \"output\": \"18:40:42.494933664: Error File below / or /root opened for writing (user=root user_loginuid=0 command=tar tar -x -f - --warning=no-timestamp parent=dpkg-deb file=md5sums program=tar container_id=1473cfd51410 image=ubuntu) container=1473cfd51410 pid=221 tid=221\",\n+ \"priority\": \"Error\",\n+ \"rule\": \"Write below root\",\n+ \"source\": \"syscall\",\n+ \"tags\": [\n+ \"filesystem\",\n+ \"mitre_persistence\"\n+ ],\n+}\n+```\n+\n+The first event is raised as a `Warning` when `/etc/shadow` is open by the\n+package manager to inform that a sensitive file has been open for read. The\n+second one triggers an `Error` when the package manager tries to untar a file\n+under the root directory. None of these actions are expected from a webserver\n+that is operating normally and should raise security alerts.\n+\n+You can also install\n+[falcosidekick](https://github.com/falcosecurity/falcosidekick) and\n+[falcosidekick-ui](https://github.com/falcosecurity/falcosidekick-ui) for better\n+ways to visualize the events.\n+\n+Now you can configure the rules and run your containers using gVisor and Falco.\n" }, { "change_type": "MODIFY", "old_path": "website/BUILD", "new_path": "website/BUILD", "diff": "@@ -166,6 +166,7 @@ docs(\n\"//g3doc/user_guide/tutorials:cni\",\n\"//g3doc/user_guide/tutorials:docker\",\n\"//g3doc/user_guide/tutorials:docker_compose\",\n+ \"//g3doc/user_guide/tutorials:falco\",\n\"//g3doc/user_guide/tutorials:knative\",\n\"//g3doc/user_guide/tutorials:kubernetes\",\n],\n" } ]
Go
Apache License 2.0
google/gvisor
Add tutorial for using Falco with gVisor PiperOrigin-RevId: 466984819
259,975
11.08.2022 17:07:51
25,200
004b4e727b308773087a18f4e63dd96560e2863d
Disable process_vm_read/writev and add a test. ProcessVM readv/writev needs some work due to lock ordering issues with locking MM between tasks. So disable the call until it can be fixed. Also add a test from one of the identified bugs from syzcaller.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/vfs2.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/vfs2.go", "diff": "@@ -156,8 +156,7 @@ func Override() {\ns.Table[299] = syscalls.Supported(\"recvmmsg\", RecvMMsg)\ns.Table[306] = syscalls.Supported(\"syncfs\", Syncfs)\ns.Table[307] = syscalls.Supported(\"sendmmsg\", SendMMsg)\n- s.Table[310] = syscalls.Supported(\"process_vm_readv\", ProcessVMReadv)\n- s.Table[311] = syscalls.Supported(\"process_vm_writev\", ProcessVMWritev)\n+ // FIXME(zkoopmans): Re-enable calls for process_vm_(read/write)v.\ns.Table[316] = syscalls.Supported(\"renameat2\", Renameat2)\ns.Table[319] = syscalls.Supported(\"memfd_create\", MemfdCreate)\ns.Table[322] = syscalls.SupportedPoint(\"execveat\", Execveat, linux.PointExecveat)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/process_vm_read_write.cc", "new_path": "test/syscalls/linux/process_vm_read_write.cc", "diff": "// limitations under the License.\n#include <asm-generic/errno-base.h>\n+#include <bits/types/siginfo_t.h>\n#include <bits/types/struct_iovec.h>\n#include <errno.h>\n#include <string.h>\n#include \"absl/strings/str_cat.h\"\n#include \"absl/strings/str_join.h\"\n#include \"test/util/linux_capability_util.h\"\n-#include \"test/util/logging.h\"\n#include \"test/util/multiprocess_util.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/test_util.h\"\n@@ -140,8 +140,8 @@ TEST_P(ProcessVMTest, TestReadvSameProcess) {\n// TestReadvSubProcess repeats the previous test in a forked process.\nTEST_P(ProcessVMTest, TestReadvSubProcess) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE((HaveCapability(CAP_SYS_PTRACE))));\nSKIP_IF(ProcessVMCallsNotSupported());\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE((HaveCapability(CAP_SYS_PTRACE))));\nauto local_data = GetParam().local_data;\nauto remote_data = GetParam().remote_data;\n@@ -190,8 +190,8 @@ TEST_P(ProcessVMTest, TestWritevSameProcess) {\n// TestWritevSubProcess repeats the previous test in a forked process.\nTEST_P(ProcessVMTest, TestWritevSubProcess) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE((HaveCapability(CAP_SYS_PTRACE))));\nSKIP_IF(ProcessVMCallsNotSupported());\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE((HaveCapability(CAP_SYS_PTRACE))));\nauto local_data = GetParam().local_data;\nauto remote_data = GetParam().remote_data;\nTestIovecs remote_iovecs(remote_data);\n@@ -282,10 +282,12 @@ TEST(ProcessVMInvalidTest, NULLRemoteIovec) {\npid_t parent = getppid();\nint ret =\nprocess_vm_readv(parent, &child_iov, contents.length(), nullptr, 1, 0);\n+ TEST_CHECK(ret == -1);\nTEST_CHECK(errno == EFAULT || errno == EINVAL);\nret =\nprocess_vm_writev(parent, &child_iov, contents.length(), nullptr, 1, 0);\n+ TEST_CHECK(ret == -1);\nTEST_CHECK(errno == EFAULT || errno == EINVAL);\n};\nASSERT_THAT(InForkedProcess(fn), IsPosixErrorOkAndHolds(0));\n@@ -377,6 +379,24 @@ TEST(ProcessVMInvalidTest, PartialReadWrite) {\nSyscallSucceedsWithValue(iov_content_1.size()));\n}\n+TEST(ProcessVMTest, WriteToZombie) {\n+ SKIP_IF(ProcessVMCallsNotSupported());\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE((HaveCapability(CAP_SYS_PTRACE))));\n+ char* data = {0};\n+ pid_t child;\n+ ASSERT_THAT(child = fork(), SyscallSucceeds());\n+ if (child == 0) {\n+ _exit(0);\n+ }\n+ siginfo_t siginfo = {};\n+ ASSERT_THAT(RetryEINTR(waitid)(P_PID, child, &siginfo, WEXITED | WNOWAIT),\n+ SyscallSucceeds());\n+ struct iovec iov;\n+ iov.iov_base = data;\n+ iov.iov_len = sizeof(data);\n+ ASSERT_THAT(process_vm_writev(child, &iov, 1, &iov, 1, 0),\n+ SyscallFailsWithErrno(ESRCH));\n+}\n} // namespace\n} // namespace testing\n" } ]
Go
Apache License 2.0
google/gvisor
Disable process_vm_read/writev and add a test. ProcessVM readv/writev needs some work due to lock ordering issues with locking MM between tasks. So disable the call until it can be fixed. Also add a test from one of the identified bugs from syzcaller. PiperOrigin-RevId: 467085160
259,909
15.08.2022 16:19:27
25,200
2dbd37fd74397994db21efb34eede3f3c9d31acd
Fix IP_ADD_MEMBERSHIP address checking to match linux. When handling a call to setsockopt for IP_ADD_MEMBERSHIP with an ip_mreqn struct with a non-zero interface IP address and interface index, Linux checks the interface index first and, if it matches a device, ignores the address. Linux: Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -1437,17 +1437,21 @@ func (s *Stack) CheckLocalAddress(nicID tcpip.NICID, protocol tcpip.NetworkProto\ns.mu.RLock()\ndefer s.mu.RUnlock()\n- // If a NIC is specified, we try to find the address there only.\n+ // If a NIC is specified, use its NIC id.\nif nicID != 0 {\nnic, ok := s.nics[nicID]\nif !ok {\nreturn 0\n}\n-\n+ // In IPv4, linux only checks the interface. If it matches, then it does\n+ // not bother with the address.\n+ // https://github.com/torvalds/linux/blob/15205c2829ca2cbb5ece5ceaafe1171a8470e62b/net/ipv4/igmp.c#L1829-L1837\n+ if protocol == header.IPv4ProtocolNumber {\n+ return nic.id\n+ }\nif nic.CheckLocalAddress(protocol, addr) {\nreturn nic.id\n}\n-\nreturn 0\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/integration/multicast_broadcast_test.go", "new_path": "pkg/tcpip/tests/integration/multicast_broadcast_test.go", "diff": "@@ -728,3 +728,52 @@ func TestUDPAddRemoveMembershipSocketOption(t *testing.T) {\n})\n}\n}\n+\n+func TestAddMembershipInterfacePrecedence(t *testing.T) {\n+ const nicID = 1\n+ multicastAddr := tcpip.Address(\"\\xe0\\x01\\x02\\x03\")\n+ proto := header.IPv4ProtocolNumber\n+ // This address is nonsensical. If the precedence is correct, this should not\n+ // matter, because ADD_IP_MEMBERSHIP should consider the interface index\n+ // and use that before checking the address.\n+ localAddr := tcpip.AddressWithPrefix{\n+ Address: testutil.MustParse4(\"8.0.8.0\"),\n+ PrefixLen: 24,\n+ }\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},\n+ })\n+ e := channel.New(0, defaultMTU, \"\")\n+ defer e.Close()\n+ if err := s.CreateNIC(nicID, e); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID, err)\n+ }\n+ protoAddr := tcpip.ProtocolAddress{Protocol: proto, AddressWithPrefix: localAddr}\n+ if err := s.AddProtocolAddress(nicID, protoAddr, stack.AddressProperties{}); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %+v, {}): %s\", nicID, protoAddr, err)\n+ }\n+\n+ var wq waiter.Queue\n+ ep, err := s.NewEndpoint(udp.ProtocolNumber, proto, &wq)\n+ if err != nil {\n+ t.Fatalf(\"NewEndpoint(%d, %d, _): %s\", udp.ProtocolNumber, proto, err)\n+ }\n+ defer ep.Close()\n+\n+ bindAddr := tcpip.FullAddress{Port: utils.LocalPort}\n+ if err := ep.Bind(bindAddr); err != nil {\n+ t.Fatalf(\"ep.Bind(%#v): %s\", bindAddr, err)\n+ }\n+\n+ memOpt := tcpip.MembershipOption{MulticastAddr: multicastAddr}\n+ memOpt.NIC = nicID\n+ memOpt.InterfaceAddr = localAddr.Address\n+\n+ // Add membership should succeed when the interface index is specified,\n+ // even if a bad interface address is specified.\n+ addOpt := tcpip.AddMembershipOption(memOpt)\n+ if err := ep.SetSockOpt(&addOpt); err != nil {\n+ t.Fatalf(\"ep.SetSockOpt(&%#v): %s\", addOpt, err)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc", "new_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc", "diff": "@@ -257,6 +257,62 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackNic) {\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n+// Check that multicast works when an interface identifier and address are\n+// provided for multicast registration. The interface should take priority.\n+TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfaceIndexAndAddr) {\n+ auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+ auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+\n+ // Bind the first FD to the loopback. This is an alternative to\n+ // IP_MULTICAST_IF for setting the default send interface.\n+ auto sender_addr = V4Loopback();\n+ ASSERT_THAT(\n+ bind(socket1->get(), AsSockAddr(&sender_addr.addr), sender_addr.addr_len),\n+ SyscallSucceeds());\n+\n+ // Bind the second FD to the v4 any address to ensure that we can receive the\n+ // multicast packet.\n+ auto receiver_addr = V4Any();\n+ ASSERT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),\n+ receiver_addr.addr_len),\n+ SyscallSucceeds());\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),\n+ &receiver_addr_len),\n+ SyscallSucceeds());\n+ EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n+\n+ // Register to receive multicast packets.\n+ ip_mreqn group = {};\n+ group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\n+ // Intentionally use an address that isn't assigned to the loopback device.\n+ // The index should take precedence.\n+ group.imr_address.s_addr = htonl(0x08080808);\n+ ASSERT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,\n+ sizeof(group)),\n+ SyscallSucceeds());\n+\n+ // Send a multicast packet.\n+ auto send_addr = V4Multicast();\n+ reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =\n+ reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;\n+ char send_buf[200];\n+ RandomizeBuffer(send_buf, sizeof(send_buf));\n+ ASSERT_THAT(\n+ RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,\n+ AsSockAddr(&send_addr.addr), send_addr.addr_len),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ // Check that we received the multicast packet.\n+ char recv_buf[sizeof(send_buf)] = {};\n+ ASSERT_THAT(\n+ RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\n+\n+ EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n+}\n+\n// Check that multicast works when the default send interface is configured by\n// IP_MULTICAST_IF, the send address is specified in sendto, and the group\n// membership is configured by address.\n" } ]
Go
Apache License 2.0
google/gvisor
Fix IP_ADD_MEMBERSHIP address checking to match linux. When handling a call to setsockopt for IP_ADD_MEMBERSHIP with an ip_mreqn struct with a non-zero interface IP address and interface index, Linux checks the interface index first and, if it matches a device, ignores the address. Linux: https://github.com/torvalds/linux/blob/15205c2829ca2cbb5ece5ceaafe1171a8470e62b/net/ipv4/igmp.c#L1829-L1837 Fixes #7880 PiperOrigin-RevId: 467787302
259,992
15.08.2022 18:11:20
25,200
2bb73c7bd7dcf0b36e774d8e82e464d04bc81f4b
Add output to `runsc trace` commands Otherwise it's hard to tell if the command succeeded or not. Updates
[ { "change_type": "MODIFY", "old_path": "runsc/cmd/trace/create.go", "new_path": "runsc/cmd/trace/create.go", "diff": "@@ -90,6 +90,7 @@ func (l *create) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}\nutil.Fatalf(\"creating session: %v\", err)\n}\n+ fmt.Printf(\"Trace session %q created.\\n\", sessionConfig.Name)\nreturn subcommands.ExitSuccess\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/trace/delete.go", "new_path": "runsc/cmd/trace/delete.go", "diff": "@@ -16,6 +16,7 @@ package trace\nimport (\n\"context\"\n+ \"fmt\"\n\"github.com/google/subcommands\"\n\"gvisor.dev/gvisor/runsc/cmd/util\"\n@@ -26,7 +27,7 @@ import (\n// delete implements subcommands.Command for the \"delete\" command.\ntype delete struct {\n- name string\n+ sessionName string\n}\n// Name implements subcommands.Command.\n@@ -47,7 +48,7 @@ func (*delete) Usage() string {\n// SetFlags implements subcommands.Command.\nfunc (l *delete) SetFlags(f *flag.FlagSet) {\n- f.StringVar(&l.name, \"name\", \"\", \"name of session to be deleted\")\n+ f.StringVar(&l.sessionName, \"name\", \"\", \"name of session to be deleted\")\n}\n// Execute implements subcommands.Command.\n@@ -56,7 +57,7 @@ func (l *delete) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}\nf.Usage()\nreturn subcommands.ExitUsageError\n}\n- if len(l.name) == 0 {\n+ if len(l.sessionName) == 0 {\nf.Usage()\nreturn util.Errorf(\"missing session name, please set --name\")\n}\n@@ -73,8 +74,10 @@ func (l *delete) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}\nutil.Fatalf(\"loading sandbox: %v\", err)\n}\n- if err := c.Sandbox.DeleteTraceSession(l.name); err != nil {\n+ if err := c.Sandbox.DeleteTraceSession(l.sessionName); err != nil {\nutil.Fatalf(\"deleting session: %v\", err)\n}\n+\n+ fmt.Printf(\"Trace session %q deleted.\\n\", l.sessionName)\nreturn subcommands.ExitSuccess\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add output to `runsc trace` commands Otherwise it's hard to tell if the command succeeded or not. Updates #4805 PiperOrigin-RevId: 467807571
259,909
16.08.2022 11:16:35
25,200
b195ca54f311b5635cb8f7ea32600f10eb57f103
Netstack: Check that the multicast address matches the endpoint protocol. Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -45,8 +45,13 @@ import (\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n-// Using header.IPv4AddressSize would cause an import cycle.\n-const ipv4AddressSize = 4\n+// Using the header package here would cause an import cycle.\n+const (\n+ ipv4AddressSize = 4\n+ ipv4ProtocolNumber = 0x0800\n+ ipv6AddressSize = 16\n+ ipv6ProtocolNumber = 0x86dd\n+)\n// Errors related to Subnet\nvar (\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/integration/BUILD", "new_path": "pkg/tcpip/tests/integration/BUILD", "diff": "@@ -120,6 +120,7 @@ go_test(\n\"//pkg/tcpip/tests/utils\",\n\"//pkg/tcpip/testutil\",\n\"//pkg/tcpip/transport/icmp\",\n+ \"//pkg/tcpip/transport/raw\",\n\"//pkg/tcpip/transport/udp\",\n\"//pkg/waiter\",\n\"@com_github_google_go_cmp//cmp:go_default_library\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/integration/multicast_broadcast_test.go", "new_path": "pkg/tcpip/tests/integration/multicast_broadcast_test.go", "diff": "@@ -32,6 +32,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/tests/utils\"\n\"gvisor.dev/gvisor/pkg/tcpip/testutil\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/icmp\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/transport/raw\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/udp\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -777,3 +778,49 @@ func TestAddMembershipInterfacePrecedence(t *testing.T) {\nt.Fatalf(\"ep.SetSockOpt(&%#v): %s\", addOpt, err)\n}\n}\n+\n+func TestMismatchedMulticastAddressAndProtocol(t *testing.T) {\n+ const nicID = 1\n+ // MulticastAddr is IPv4, but proto is IPv6.\n+ multicastAddr := tcpip.Address(\"\\xe0\\x01\\x02\\x03\")\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{icmp.NewProtocol6},\n+ RawFactory: raw.EndpointFactory{},\n+ })\n+ e := channel.New(0, defaultMTU, \"\")\n+ defer e.Close()\n+ if err := s.CreateNIC(nicID, e); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID, err)\n+ }\n+ protoAddr := tcpip.ProtocolAddress{Protocol: header.IPv4ProtocolNumber, AddressWithPrefix: utils.Ipv4Addr}\n+ if err := s.AddProtocolAddress(nicID, protoAddr, stack.AddressProperties{}); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %+v, {}): %s\", nicID, protoAddr, err)\n+ }\n+\n+ var wq waiter.Queue\n+ ep, err := s.NewRawEndpoint(header.ICMPv6ProtocolNumber, header.IPv6ProtocolNumber, &wq, false)\n+ if err != nil {\n+ t.Fatalf(\"NewEndpoint(%d, %d, _): %s\", udp.ProtocolNumber, header.IPv6ProtocolNumber, err)\n+ }\n+ defer ep.Close()\n+\n+ bindAddr := tcpip.FullAddress{Port: utils.LocalPort}\n+ if err := ep.Bind(bindAddr); err != nil {\n+ t.Fatalf(\"ep.Bind(%#v): %s\", bindAddr, err)\n+ }\n+\n+ memOpt := tcpip.MembershipOption{\n+ MulticastAddr: multicastAddr,\n+ NIC: 0,\n+ InterfaceAddr: utils.Ipv4Addr.Address,\n+ }\n+\n+ // Add membership should succeed when the interface index is specified,\n+ // even if a bad interface address is specified.\n+ addOpt := tcpip.AddMembershipOption(memOpt)\n+ expErr := &tcpip.ErrInvalidOptionValue{}\n+ if err := ep.SetSockOpt(&addOpt); err != expErr {\n+ t.Fatalf(\"ep.SetSockOpt(&%#v): want %q, got %q\", addOpt, expErr, err)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/internal/network/endpoint.go", "new_path": "pkg/tcpip/transport/internal/network/endpoint.go", "diff": "@@ -915,7 +915,7 @@ func (e *Endpoint) SetSockOpt(opt tcpip.SettableSocketOption) tcpip.Error {\ne.multicastAddr = addr\ncase *tcpip.AddMembershipOption:\n- if !header.IsV4MulticastAddress(v.MulticastAddr) && !header.IsV6MulticastAddress(v.MulticastAddr) {\n+ if !(header.IsV4MulticastAddress(v.MulticastAddr) && e.netProto == header.IPv4ProtocolNumber) && !(header.IsV6MulticastAddress(v.MulticastAddr) && e.netProto == header.IPv6ProtocolNumber) {\nreturn &tcpip.ErrInvalidOptionValue{}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Netstack: Check that the multicast address matches the endpoint protocol. Reported-by: syzbot+a72cb94d1b5a6f5f0e11@syzkaller.appspotmail.com PiperOrigin-RevId: 467975743
259,992
16.08.2022 12:26:06
25,200
919a20f17913de17355ddccd5eb8d117b7ddbb8b
Add documentation and tutorials for Runtime Monitoring Updates
[ { "change_type": "ADD", "old_path": null, "new_path": "examples/seccheck/README.md", "diff": "+This directory provides an example of a monitoring process that receives\n+connections from gVisor sandboxes and prints the traces to `stdout`. The example\n+contains two main files:\n+\n+* server.cc: this is where `main()` and all the code is. It sets up a server\n+ listening to a Unix-domain socket located at `/tmp/gvisor_events.sock` or a\n+ configurable location via a command line argument.\n+* pod_init.json: this file contains the trace configuration that should be\n+ passed to `runsc`. It can be done either via `--pod-init-config` flag or\n+ using `runsc trace create` command. Note that the socket location is\n+ specified in this file, in case you change it.\n+\n+# Usage\n+\n+Let's first start the server, which waits for new connections:\n+\n+```shell\n+$ bazel run examples/seccheck:server_cc\n+Socket address /tmp/gvisor_events.sock\n+```\n+\n+Here is a simple example using `runsc do`:\n+\n+```shell\n+runsc --rootless --network=none --pod-init-config=examples/seccheck/pod_init.json do echo 123\n+```\n+\n+Back at the server terminal, you can see the following traces being outputted:\n+\n+```\n+Connection accepted\n+Start => id: \"runsc-329739\" cwd: \"/home/fvoznika\" args: \"echo\" args: \"123\"\n+E Open sysno: 257 fd: -100 pathname: \"/usr/lib/x86_64-linux-gnu/glibc-hwcaps/x86-64-v3/libc.so.6\" flags: 524288\n+X Open exit { errorno: 2 } sysno: 257 fd: -100 pathname: \"/usr/lib/x86_64-linux-gnu/glibc-hwcaps/x86-64-v3/libc.so.6\" flags: 524288\n+E Open sysno: 257 fd: -100 pathname: \"/usr/lib/x86_64-linux-gnu/glibc-hwcaps/x86-64-v2/libc.so.6\" flags: 524288\n+X Open exit { errorno: 2 } sysno: 257 fd: -100 pathname: \"/usr/lib/x86_64-linux-gnu/glibc-hwcaps/x86-64-v2/libc.so.6\" flags: 524288\n+...\n+TaskExit =>\n+Connection closed\n+```\n+\n+Connection messages indicate when `runsc` connected and disconnected to/from the\n+server. Then there is a trace for container start and a few syscalls to\n+`open(2)` for searching libraries. You can change `pod_init.json` to configure\n+the trace session to your liking.\n+\n+To set this up with Docker, you can add the `--pod-init-config` flag when the\n+runtime is installed:\n+\n+```shell\n+$ sudo runsc install --runtime=runsc-trace -- --pod-init-config=$PWD/examples/seccheck/pod_init.json\n+$ sudo systemctl restart docker\n+$ docker run --rm --runtime=runsc-trace hello-world\n+```\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/seccheck/README.md", "diff": "+# Introduction\n+\n+This package provides a remote interface to observe behavior of the application\n+running inside the sandbox. It was built with runtime monitoring in mind, e.g.\n+threat detection, but it can be used for other purposes as well. It allows a\n+process running outside the sandbox to receive a stream of trace data\n+asynchronously. This process can watch actions performed by the application,\n+generate alerts when something unexpected occurs, log these actions, etc.\n+\n+First, let's go over a few concepts before we get into the details.\n+\n+## Concepts\n+\n+- **Points:** these are discrete places (or points) in the code where\n+ instrumentation was added. Each point has a unique name and schema. They can\n+ be individually enabled/disabled. For example, `container/start` is a point\n+ that is fired when a new container starts.\n+- **Point fields:** each point may contain fields that carry point data. For\n+ example, `container/start` has a `id` field with the container ID that is\n+ getting started.\n+- **Optional fields:** each point may also have optional fields. By default\n+ these fields are not collected and they can be manually set to be collected\n+ when the point is configured. These fields are normally more expensive to\n+ collect and/or large, e.g. resolve path to FD, or data for read/write.\n+- **Context fields:** these are fields generally available to most events, but\n+ are disabled by default. Like optional fields, they can be set to be\n+ collected when the point is configured. Context field data comes from\n+ context where the point is being fired, for example PID, UID/GID, container\n+ ID are fields available to most trace points.\n+- **Sink:** sinks are trace point consumers. Each sink is identified by a name\n+ and may handle trace points differently. Later we'll describe in more\n+ detailed what sinks are available in the system and how to use them.\n+- **Session:** trace session is a set of points that are enabled with their\n+ corresponding configuration. A trace session also has a list of sinks that\n+ will receive the trace points. A session is identified by a unique name.\n+ Once a session is deleted, all points belonging to the session are disabled\n+ and the sinks destroyed.\n+\n+If you're interested in exploring further, there are more details in the\n+[design doc](https://docs.google.com/document/d/1RQQKzeFpO-zOoBHZLA-tr5Ed_bvAOLDqgGgKhqUff2A/edit).\n+\n+# Points\n+\n+Every trance point in the system is identified by a unique name. The naming\n+convention is to scope the point with a main component followed by its name to\n+avoid conflicts. Here are a few examples:\n+\n+- `sentry/signal_delivered`\n+- `container/start`\n+- `syscall/openat/enter`\n+\n+> Note: the syscall trace point contains an extra level to separate the\n+> enter/exit points.\n+\n+Most of the trace points are in the `syscall` component. They come in 2 flavors:\n+raw, schematized. Raw syscalls include all syscalls in the system and contain\n+the 6 arguments for the given syscall. Schematized trace points exist for many\n+syscalls, but not all. They provide fields that are specific to the syscalls and\n+fetch more information than is available from the raw syscall arguments. For\n+example, here is the schema for the open syscall:\n+\n+```proto\n+message Open {\n+ gvisor.common.ContextData context_data = 1;\n+ Exit exit = 2;\n+ uint64 sysno = 3;\n+ int64 fd = 4;\n+ string fd_path = 5;\n+ string pathname = 6;\n+ uint32 flags = 7;\n+ uint32 mode = 8;\n+}\n+```\n+\n+As you can see, come fields are in both raw and schemitized points, like `fd`\n+which is also `arg1` in the raw syscall, but here it has a name and correct\n+type. It also has fields like `pathname` that are not available in the raw\n+syscall event. In addition, `fd_path` is an optional field that can take the\n+`fd` and translate it into a full path for convenience. In some cases, the same\n+schema can be shared by many syscalls. In this example, `message Open` is used\n+for `open(2)`, `openat(2)` and `creat(2)` syscalls. The `sysno` field can be\n+used to distinguish between them. The schema for all syscall trace points can be\n+found\n+[here](https://cs.opensource.google/gvisor/gvisor/+/master:pkg/sentry/seccheck/points/syscall.proto).\n+\n+Other components that exist today are:\n+\n+* **sentry:** trace points fired from within gVisor's kernel\n+ ([schema](https://cs.opensource.google/gvisor/gvisor/+/master:pkg/sentry/seccheck/points/sentry.proto)).\n+* **container:** container related events\n+ ([schema](https://cs.opensource.google/gvisor/gvisor/+/master:pkg/sentry/seccheck/points/container.proto)).\n+\n+The following command lists all trace points available in the system:\n+\n+```shell\n+$ runsc trace metadata\n+POINTS (973)\n+Name: container/start, optional fields: [env], context fields: [time|thread_id|task_start_time|group_id|thread_group_start_time|container_id|credentials|cwd|process_name]\n+Name: sentry/clone, optional fields: [], context fields: [time|thread_id|task_start_time|group_id|thread_group_start_time|container_id|credentials|cwd|process_name]\n+Name: syscall/accept/enter, optional fields: [fd_path], context fields: [time|thread_id|task_start_time|group_id|thread_group_start_time|container_id|credentials|cwd|process_name]\n+...\n+```\n+\n+> Note: the output format for `trace metadata` may change without notice.\n+\n+The list above also includes what optional and context fields are available for\n+each trace point. Optional fields schema is part of the trace point proto, like\n+`fd_path` we saw above. Context fields are set in `context_data` field of all\n+points and is defined in\n+[gvisor.common.ContextData](https://cs.opensource.google/gvisor/gvisor/+/master:pkg/sentry/seccheck/points/common.proto;bpv=1;bpt=1;l=77?gsn=ContextData&gs=kythe%3A%2F%2Fgithub.com%2Fgoogle%2Fgvisor%3Flang%3Dprotobuf%3Fpath%3Dpkg%2Fsentry%2Fseccheck%2Fpoints%2Fcommon.proto%234.2).\n+\n+# Sinks\n+\n+Sinks receive enabled trace points and do something useful with them. They are\n+identified by a unique name. The same `runsc trace metadata` command used above\n+also lists all sinks:\n+\n+```shell\n+$ runsc trace metadata\n+...\n+SINKS (2)\n+Name: remote\n+Name: null\n+\n+```\n+\n+> Note: the output format for `trace metadata` may change without notice.\n+\n+## Remote\n+\n+The remote sink serializes the trace point into protobuf and sends it to a\n+separate process. For threat detection, external monitoring processes can\n+receive connections from remote sinks and be sent a stream of trace points that\n+are occurring in the system. This sink connects to a remote process via\n+Unix-domain socket and expect the remote process to be listening for new\n+connections. If you're interested about creating a monitoring process that\n+communicates with the remote sink, [this document](sinks/remote/README.md) has\n+more details.\n+\n+The remote sink has many properties that can be configured when its created\n+(more on how to configure sinks below):\n+\n+* endpoint (mandatory): Unix-domain socket address to connect.\n+* retries: number of attempts to write the trace point before dropping it in\n+ case the remote process is not responding. Note that a high number of\n+ retries can significantly delay application execution.\n+* backoff: initial backoff time after the first failed attempt. This value\n+ doubles every failed attempts up to the max.\n+* backoff_max: max duration to wait between retries.\n+\n+## Null\n+\n+The null sink does nothing with the trace points and it's used for testing.\n+Syscall tests enable all trace points, with all optional and context fields to\n+ensure there is no crash with them enabled.\n+\n+## Strace (not implemented)\n+\n+The strace sink has not been implemented yet. It's meant to replace the strace\n+mechanism that exists in the Sentry to simplify the code and add more trace\n+points to it.\n+\n+> Note: It requires more than one trace session to be supported.\n+\n+# Sessions\n+\n+Trace sessions scope a set of trace point with their corresponding configuration\n+and a set of sinks that receives the points. Sessions can be created at sandbox\n+initialization time or during runtime. Creating sessions at init time guarantees\n+that no trace points are missed, which is important for threat detection. It is\n+configured using the `--pod-init-config` flag (more on it below). To manage\n+sessions during runtime, `runsc trace create|delete|list` is used to manipulate\n+trace sessions. Here are few examples assuming there is a running container with\n+ID=cont123 using Docker:\n+\n+```shell\n+$ sudo runsc --root /run/docker/runtime-runc/moby trace create --config session.json cont123\n+$ sudo runsc --root /run/docker/runtime-runc/moby trace list cont123\n+SESSIONS (1)\n+\"Default\"\n+ Sink: \"remote\", dropped: 0\n+\n+$ sudo runsc --root /var/run/docker/runtime-runc/moby trace delete --name Default cont123\n+$ sudo runsc --root /var/run/docker/runtime-runc/moby trace list cont123\n+SESSIONS (0)\n+```\n+\n+> Note: There is a current limitation that only a single session can exist in\n+> the system and it must be called `Default`. This restriction can be lifted in\n+> the future when more than one session is needed.\n+\n+## Config\n+\n+The event session can be defined using JSON for the `runsc trace create`\n+command. The session definition has 3 mains parts:\n+\n+1. `name`: name of the session being created. Only `Default` for now.\n+1. `points`: array of points being enabled in the session. Each point has:\n+ 1. `name`: name of trace point being enabled.\n+ 1. `optional_fields`: array of optional fields to include with the trace\n+ point.\n+ 1. `context_fields`: array of context fields to include with the trace\n+ point.\n+1. `sinks`: array of sinks that will process the trace points.\n+ 1. `name`: name of the sink.\n+ 1. `config`: sink specific configuration.\n+ 1. `ignore_setup_error`: ignores failure to configure the sink. In the\n+ remote sink case, for example, it doesn't fail container startup if the\n+ remote process cannot be reached.\n+\n+The session configuration above can also be used with the `--pod-init-config`\n+flag under the `\"trace_session\"` JSON object. There is a full example\n+[here](https://cs.opensource.google/gvisor/gvisor/+/master:examples/seccheck/pod_init.json)\n+\n+> Note: For convenience, the `--pod-init-config` file can also be used with\n+> `runsc trace create` command. The portions of the Pod init config file that\n+> are not related to the session configuration are ignored.\n+\n+# Full Example\n+\n+Here, we're going to explore a how to use runtime monitoring end to end. Under\n+the `examples` directory there is an implementation of the monitoring process\n+that accepts connections from remote sinks and prints out all the trace points\n+it receives.\n+\n+First, let's start the monitoring process and leave it running:\n+\n+```shell\n+$ bazel run examples/seccheck:server_cc\n+Socket address /tmp/gvisor_events.sock\n+```\n+\n+The server is now listening on the socket at `/tmp/gvisor_events.sock` for new\n+gVisor sandboxes to connect. Now let's create a session configuration file with\n+some trace points enabled and the remote sink using the socket address from\n+above:\n+\n+```shell\n+$ cat <<EOF >session.json\n+{\n+ \"trace_session\": {\n+ \"name\": \"Default\",\n+ \"points\": [\n+ {\n+ \"name\": \"sentry/clone\"\n+ },\n+ {\n+ \"name\": \"syscall/fork/enter\",\n+ \"context_fields\": [\n+ \"group_id\",\n+ \"process_name\"\n+ ]\n+ },\n+ {\n+ \"name\": \"syscall/fork/exit\",\n+ \"context_fields\": [\n+ \"group_id\",\n+ \"process_name\"\n+ ]\n+ },\n+ {\n+ \"name\": \"syscall/execve/enter\",\n+ \"context_fields\": [\n+ \"group_id\",\n+ \"process_name\"\n+ ]\n+ },\n+ {\n+ \"name\": \"syscall/sysno/35/enter\",\n+ \"context_fields\": [\n+ \"group_id\",\n+ \"process_name\"\n+ ]\n+ },\n+ {\n+ \"name\": \"syscall/sysno/35/exit\"\n+ }\n+ ],\n+ \"sinks\": [\n+ {\n+ \"name\": \"remote\",\n+ \"config\": {\n+ \"endpoint\": \"/tmp/gvisor_events.sock\"\n+ }\n+ }\n+ ]\n+ }\n+}\n+EOF\n+```\n+\n+Now, we're ready to start a container and watch it send traces to the monitoring\n+process. The container we're going to create simply loops every 5 seconds and\n+writes something to stdout. While the container is running, we're going to call\n+`runsc trace` command to create a trace session.\n+\n+```shell\n+# Start the container and copy the container ID for future reference.\n+$ docker run --rm --runtime=runsc -d bash -c \"while true; do echo looping; sleep 5; done\"\n+dee0da1eafc6b15abffeed1abc6ca968c6d816252ae334435de6f3871fb05e61\n+\n+$ CID=dee0da1eafc6b15abffeed1abc6ca968c6d816252ae334435de6f3871fb05e61\n+\n+# Create new trace session in the container above.\n+$ sudo runsc --root /var/run/docker/runtime-runc/moby trace create --config session.json ${CID?}\n+Trace session \"Default\" created.\n+```\n+\n+In the terminal that you are running the monitoring process, you'll start seeing\n+messages like this:\n+\n+```\n+Connection accepted\n+E Fork context_data { thread_group_id: 1 process_name: \"bash\" } sysno: 57\n+CloneInfo => created_thread_id: 110 created_thread_group_id: 110 created_thread_start_time_ns: 1660249219204031676\n+X Fork context_data { thread_group_id: 1 process_name: \"bash\" } exit { result: 110 } sysno: 57\n+E Execve context_data { thread_group_id: 110 process_name: \"bash\" } sysno: 59 pathname: \"/bin/sleep\" argv: \"sleep\" argv: \"5\"\n+E Syscall context_data { thread_group_id: 110 process_name: \"sleep\" } sysno: 35 arg1: 139785970818200 arg2: 139785970818200\n+X Syscall context_data { thread_group_id: 110 process_name: \"sleep\" } exit { } sysno: 35 arg1: 139785970818200 arg2: 139785970818200\n+```\n+\n+The first message in the log is a notification that a new sandbox connected to\n+the monitoring process. The `E` and `X` in front of the syscall traces denotes\n+whether the trace belongs to an `E`nter or e`X`it syscall trace. The first\n+syscall trace shows a call to `fork(2)` from a process with `group_thread_id`\n+(or PID) equal to 1 and the process name is `bash`. In other words, this is the\n+init process of the container, running `bash`, and calling fork to execute\n+`sleep 5`. The next trace is from `sentry/clone` and informs that the forked\n+process has PID=110. Then, `X Fork` indicates that `fork(2)` syscall returned to\n+the parent. The child continues and executes `execve(2)` to call `sleep` as can\n+be seen from the `pathname` and `argv` fields. Note that at this moment, the PID\n+is 110 (child) but the process name is still `bash` because it hasn't executed\n+`sleep` yet. After `execve(2)` is called the process name changes to `sleep` as\n+expected. Next, it shows the `nanosleep(2)` raw syscalls which has `sysno`=35\n+(it's referred as `syscall/sysno/35` in the configuration file. One for enter\n+with the exit trace happening 5 seconds later.\n+\n+Let's list all trace session that are active in the sandbox:\n+\n+```shell\n+$ sudo runsc --root /var/run/docker/runtime-runc/moby trace list ${CID?}\n+SESSIONS (1)\n+\"Default\"\n+ Sink: \"remote\", dropped: 0\n+```\n+\n+It shows the `Default` session created above, using the `remote` sink and no\n+trace points have been dropped. Once we're done, the trace session can be\n+deleted with the command below:\n+\n+```shell\n+$ sudo runsc --root /var/run/docker/runtime-runc/moby trace delete --name\n+Default ${CID?} Trace session \"Default\" deleted.\n+```\n+\n+In the monitoring process you should see a message `Connection closed` to inform\n+that the sandbox has disconnected.\n+\n+If you want to set up `runsc` to connect to the monitoring process automatically\n+before the application starts running, you can set the `--pod-init-config` flag\n+to the configuration file created above. Here's an example:\n+\n+```shell\n+$ sudo runsc --install --runtime=runsc-trace -- --pod-init-config=$PWD/session.json\n+```\n" } ]
Go
Apache License 2.0
google/gvisor
Add documentation and tutorials for Runtime Monitoring Updates #4805 PiperOrigin-RevId: 467993824
259,868
16.08.2022 16:06:43
25,200
4b7922fa0bbeb90426ec4f2886d4edbbabd6751d
`iperf` benchmark: Use container networking links rather than default bridge. This fixes `iperf` getting stuck on some versions of Docker, and mirrors the way other multi-container tests do networking.
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/network/iperf_test.go", "new_path": "test/benchmarks/network/iperf_test.go", "diff": "@@ -15,8 +15,10 @@ package network\nimport (\n\"context\"\n+ \"fmt\"\n\"os\"\n\"testing\"\n+ \"time\"\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n\"gvisor.dev/gvisor/pkg/test/testutil\"\n@@ -80,20 +82,8 @@ func BenchmarkIperf(b *testing.B) {\n}, \"iperf\", \"-s\"); err != nil {\nb.Fatalf(\"failed to start server with: %v\", err)\n}\n-\n- ip, err := serverMachine.IPAddress()\n- if err != nil {\n- b.Fatalf(\"failed to find server ip: %v\", err)\n- }\n-\n- servingPort, err := server.FindPort(ctx, port)\n- if err != nil {\n- b.Fatalf(\"failed to find port %d: %v\", port, err)\n- }\n-\n- // Make sure the server is up and serving before we run.\n- if err := harness.WaitUntilServing(ctx, clientMachine, ip, servingPort); err != nil {\n- b.Fatalf(\"failed to wait for server: %v\", err)\n+ if out, err := server.WaitForOutput(ctx, fmt.Sprintf(\"Server listening on TCP port %d\", port), 10*time.Second); err != nil {\n+ b.Fatalf(\"failed to wait for iperf server: %v %s\", err, out)\n}\niperf := tools.Iperf{\n@@ -104,7 +94,8 @@ func BenchmarkIperf(b *testing.B) {\nb.ResetTimer()\nout, err := client.Run(ctx, dockerutil.RunOpts{\nImage: \"benchmarks/iperf\",\n- }, iperf.MakeCmd(ip, servingPort)...)\n+ Links: []string{server.MakeLink(\"iperfsrv\")},\n+ }, iperf.MakeCmd(\"iperfsrv\", port)...)\nif err != nil {\nb.Fatalf(\"failed to run client: %v\", err)\n}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/tools/iperf.go", "new_path": "test/benchmarks/tools/iperf.go", "diff": "@@ -16,7 +16,6 @@ package tools\nimport (\n\"fmt\"\n- \"net\"\n\"regexp\"\n\"strconv\"\n\"testing\"\n@@ -30,14 +29,14 @@ type Iperf struct {\n}\n// MakeCmd returns a iperf client command.\n-func (i *Iperf) MakeCmd(ip net.IP, port int) []string {\n+func (i *Iperf) MakeCmd(host string, port int) []string {\nreturn []string{\n\"iperf\",\n\"--format\", \"K\", // Output in KBytes.\n\"--realtime\", // Measured in realtime.\n\"--num\", fmt.Sprintf(\"%dK\", i.Num), // Number of bytes to send in KB.\n\"--length\", fmt.Sprintf(\"%d\", length),\n- \"--client\", ip.String(),\n+ \"--client\", host,\n\"--port\", fmt.Sprintf(\"%d\", port),\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
`iperf` benchmark: Use container networking links rather than default bridge. This fixes `iperf` getting stuck on some versions of Docker, and mirrors the way other multi-container tests do networking. PiperOrigin-RevId: 468049041
259,868
16.08.2022 17:03:48
25,200
5d08a59813201143d3efe103c2265c56ff6270c8
Makefile: Add option to not benchmark `runc`. This is useful when wanting to run benchmarks in a way where the output can be captured to a file, such that this file only contains one platform's specific performance data.
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -366,6 +366,7 @@ containerd-tests: containerd-test-1.6.0\n## BENCHMARKS_OFFICIAL - marks the data as official.\n## BENCHMARKS_PLATFORMS - if set, only run the benchmarks for this\n## space-separated list of platform names.\n+## BENCHMARKS_RUNC - if true, also benchmark runc performance.\n## BENCHMARKS_FILTER - filter to be applied to the test suite.\n## BENCHMARKS_OPTIONS - options to be passed to the test.\n## BENCHMARKS_PROFILE - profile options to be passed to the test.\n@@ -376,12 +377,13 @@ BENCHMARKS_TABLE ?= benchmarks\nBENCHMARKS_SUITE ?= ffmpeg\nBENCHMARKS_UPLOAD ?= false\nBENCHMARKS_OFFICIAL ?= false\n-BENCHMARKS_TARGETS := //test/benchmarks/media:ffmpeg_test\n+BENCHMARKS_TARGETS ?= //test/benchmarks/media:ffmpeg_test\nBENCHMARKS_PLATFORMS ?=\n-BENCHMARKS_FILTER := .\n-BENCHMARKS_OPTIONS := -test.benchtime=30s\n-BENCHMARKS_ARGS := -test.v -test.bench=$(BENCHMARKS_FILTER) $(BENCHMARKS_OPTIONS)\n-BENCHMARKS_PROFILE := -pprof-dir=/tmp/profile -pprof-cpu -pprof-heap -pprof-block -pprof-mutex\n+BENCHMARKS_RUNC ?= true\n+BENCHMARKS_FILTER ?= .\n+BENCHMARKS_OPTIONS ?= -test.benchtime=30s\n+BENCHMARKS_ARGS ?= -test.v -test.bench=$(BENCHMARKS_FILTER) $(BENCHMARKS_OPTIONS)\n+BENCHMARKS_PROFILE ?= -pprof-dir=/tmp/profile -pprof-cpu -pprof-heap -pprof-block -pprof-mutex\ninit-benchmark-table: ## Initializes a BigQuery table with the benchmark schema.\n@$(call run,//tools/parsers:parser,init --project=$(BENCHMARKS_PROJECT) --dataset=$(BENCHMARKS_DATASET) --table=$(BENCHMARKS_TABLE))\n@@ -413,7 +415,9 @@ benchmark-platforms: load-benchmarks $(RUNTIME_BIN) ## Runs benchmarks for runc\n$(call run_benchmark,$${PLATFORM}); \\\ndone; \\\nfi\n- @$(call run_benchmark,runc)\n+ @set -xe; if test \"$(BENCHMARKS_RUNC)\" == true; then \\\n+ $(call run_benchmark,runc); \\\n+ fi\n.PHONY: benchmark-platforms\nrun-benchmark: load-benchmarks ## Runs single benchmark and optionally sends data to BigQuery.\n" } ]
Go
Apache License 2.0
google/gvisor
Makefile: Add option to not benchmark `runc`. This is useful when wanting to run benchmarks in a way where the output can be captured to a file, such that this file only contains one platform's specific performance data. PiperOrigin-RevId: 468061772
259,919
17.08.2022 17:28:08
25,200
5f471ac269c224299e3fbe873a2e214136bc74fa
Fix minor typo in production.md
[ { "change_type": "MODIFY", "old_path": "g3doc/user_guide/production.md", "new_path": "g3doc/user_guide/production.md", "diff": "@@ -32,7 +32,7 @@ used to sandbox **every** application.\n## Attack surface reduction {#attack-surface}\n-Because sandboxing comes woth some performance overhead, you should first\n+Because sandboxing comes with some performance overhead, you should first\ninvestigate ways to **reduce your outside attack surface** (without such\noverhead) as much as possible, prior to introducing sandboxing into your\nproduction stack at all.\n" } ]
Go
Apache License 2.0
google/gvisor
Fix minor typo in production.md
259,854
13.08.2022 14:56:37
25,200
ec66002f34b7783e3487fe852d607df17a43f430
Fix double gonet.(*TCPListener).Shutdown panic. * Fix a panic that would occur when calling gonet.(*TCPListener).Shutdown twice. * Add test for gonet.(*TCPListener).Shutdown and gonet.(*TCPListener).Close unblocking gonet.(*TCPListener).Accept.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/adapters/gonet/gonet.go", "new_path": "pkg/tcpip/adapters/gonet/gonet.go", "diff": "@@ -50,6 +50,7 @@ type TCPListener struct {\nstack *stack.Stack\nep tcpip.Endpoint\nwq *waiter.Queue\n+ cancelOnce sync.Once\ncancel chan struct{}\n}\n@@ -112,7 +113,9 @@ func (l *TCPListener) Close() error {\n// Shutdown stops the HTTP server.\nfunc (l *TCPListener) Shutdown() {\nl.ep.Shutdown(tcpip.ShutdownWrite | tcpip.ShutdownRead)\n+ l.cancelOnce.Do(func() {\nclose(l.cancel) // broadcast cancellation\n+ })\n}\n// Addr implements net.Listener.Addr.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/adapters/gonet/gonet_test.go", "new_path": "pkg/tcpip/adapters/gonet/gonet_test.go", "diff": "@@ -807,6 +807,105 @@ func TestDialContextTCPTimeout(t *testing.T) {\n}\n}\n+// TestInterruptListender tests that (*TCPListener).Accept can be interrupted.\n+func TestInterruptListender(t *testing.T) {\n+ for _, test := range []struct {\n+ name string\n+ stop func(l *TCPListener) error\n+ }{\n+ {\n+ \"Close\",\n+ (*TCPListener).Close,\n+ },\n+ {\n+ \"Shutdown\",\n+ func(l *TCPListener) error {\n+ l.Shutdown()\n+ return nil\n+ },\n+ },\n+ {\n+ \"Double Shutdown\",\n+ func(l *TCPListener) error {\n+ l.Shutdown()\n+ l.Shutdown()\n+ return nil\n+ },\n+ },\n+ } {\n+ t.Run(test.name, func(t *testing.T) {\n+ s, err := newLoopbackStack()\n+ if err != nil {\n+ t.Fatalf(\"newLoopbackStack() = %v\", err)\n+ }\n+ defer func() {\n+ s.Close()\n+ s.Wait()\n+ }()\n+\n+ addr := tcpip.FullAddress{NICID, tcpip.Address(net.IPv4(169, 254, 10, 1).To4()), 11211}\n+\n+ protocolAddr := tcpip.ProtocolAddress{\n+ Protocol: ipv4.ProtocolNumber,\n+ AddressWithPrefix: addr.Addr.WithPrefix(),\n+ }\n+ if err := s.AddProtocolAddress(NICID, protocolAddr, stack.AddressProperties{}); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %+v, {}): %s\", NICID, protocolAddr, err)\n+ }\n+\n+ l, e := ListenTCP(s, addr, ipv4.ProtocolNumber)\n+ if e != nil {\n+ t.Fatalf(\"NewListener() = %v\", e)\n+ }\n+ defer l.Close()\n+ done := make(chan struct{})\n+ go func() {\n+ defer close(done)\n+ c, err := l.Accept()\n+ if err != nil {\n+ // Accept is expected to return an error.\n+ t.Log(\"Accept #1:\", err)\n+ return\n+ }\n+ t.Errorf(\"Accept #1 returned a connection: %v -> %v\", c.LocalAddr(), c.RemoteAddr())\n+ c.Close()\n+ }()\n+\n+ // Give l.Accept a chance to block before stopping it.\n+ time.Sleep(time.Millisecond * 50)\n+\n+ if err := test.stop(l); err != nil {\n+ t.Error(\"stop:\", err)\n+ }\n+\n+ select {\n+ case <-done:\n+ case <-time.After(5 * time.Second):\n+ t.Errorf(\"c.Accept didn't unblock\")\n+ }\n+\n+ done = make(chan struct{})\n+ go func() {\n+ defer close(done)\n+ c, err := l.Accept()\n+ if err != nil {\n+ // Accept is expected to return an error.\n+ t.Log(\"Accept #2:\", err)\n+ return\n+ }\n+ t.Errorf(\"Accept #2 returned a connection: %v -> %v\", c.LocalAddr(), c.RemoteAddr())\n+ c.Close()\n+ }()\n+\n+ select {\n+ case <-done:\n+ case <-time.After(5 * time.Second):\n+ t.Errorf(\"c.Accept didn't unblock a second time\")\n+ }\n+ })\n+ }\n+}\n+\nfunc TestNetTest(t *testing.T) {\nnettest.TestConn(t, makePipe)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix double gonet.(*TCPListener).Shutdown panic. * Fix a panic that would occur when calling gonet.(*TCPListener).Shutdown twice. * Add test for gonet.(*TCPListener).Shutdown and gonet.(*TCPListener).Close unblocking gonet.(*TCPListener).Accept.
259,985
23.08.2022 23:59:21
25,200
00e0718041e44ea4cb51f1710f1170ab4980a972
Allow creation of new FS objects from outside the vfs package.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/mount.go", "new_path": "pkg/sentry/vfs/mount.go", "diff": "@@ -174,6 +174,22 @@ func (vfs *VirtualFilesystem) NewMountNamespace(ctx context.Context, creds *auth\nreturn mntns, nil\n}\n+// NewFilesystem creates a new filesystem object not yet associated with any\n+// mounts. It can be installed into the filesystem tree with ConnectMountAt.\n+// Note that only the filesystem-specific mount options from opts are used by\n+// this function, mount flags are ignored. To set mount flags, pass them to a\n+// corresponding ConnectMountAt.\n+func (vfs *VirtualFilesystem) NewFilesystem(ctx context.Context, creds *auth.Credentials, source, fsTypeName string, opts *MountOptions) (*Filesystem, *Dentry, error) {\n+ rft := vfs.getFilesystemType(fsTypeName)\n+ if rft == nil {\n+ return nil, nil, linuxerr.ENODEV\n+ }\n+ if !opts.InternalMount && !rft.opts.AllowUserMount {\n+ return nil, nil, linuxerr.ENODEV\n+ }\n+ return rft.fsType.GetFilesystem(ctx, vfs, creds, source, opts.GetFilesystemOptions)\n+}\n+\n// NewDisconnectedMount returns a Mount representing fs with the given root\n// (which may be nil). The new Mount is not associated with any MountNamespace\n// and is not connected to any other Mounts. References are taken on fs and\n@@ -190,14 +206,7 @@ func (vfs *VirtualFilesystem) NewDisconnectedMount(fs *Filesystem, root *Dentry,\n// then returns a Mount representing it. The new Mount is not associated with\n// any MountNamespace and is not connected to any other Mounts.\nfunc (vfs *VirtualFilesystem) MountDisconnected(ctx context.Context, creds *auth.Credentials, source string, fsTypeName string, opts *MountOptions) (*Mount, error) {\n- rft := vfs.getFilesystemType(fsTypeName)\n- if rft == nil {\n- return nil, linuxerr.ENODEV\n- }\n- if !opts.InternalMount && !rft.opts.AllowUserMount {\n- return nil, linuxerr.ENODEV\n- }\n- fs, root, err := rft.fsType.GetFilesystem(ctx, vfs, creds, source, opts.GetFilesystemOptions)\n+ fs, root, err := vfs.NewFilesystem(ctx, creds, source, fsTypeName, opts)\nif err != nil {\nreturn nil, err\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Allow creation of new FS objects from outside the vfs package. PiperOrigin-RevId: 469649194
259,907
24.08.2022 09:46:34
25,200
51c48824f0a86b59c5c26a1cfda45cfdd618aee2
Fix TODO comment for issue 6319. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/kernel.go", "new_path": "pkg/sentry/kernel/kernel.go", "diff": "@@ -88,7 +88,7 @@ var VFS2Enabled = false\n// LISAFSEnabled is set to true when lisafs protocol is enabled. Added as a\n// global to allow easy access everywhere.\n//\n-// TODO(gvisor.dev/issue/6319): Remove when lisafs is default.\n+// TODO(gvisor.dev/issue/7911): Remove when 9P is deleted.\nvar LISAFSEnabled = false\n// FUSEEnabled is set to true when FUSE is enabled. Added as a global to allow\n" } ]
Go
Apache License 2.0
google/gvisor
Fix TODO comment for issue 6319. Fixes #6319 PiperOrigin-RevId: 469752297
259,907
24.08.2022 10:53:39
25,200
2ee98e784b080498983bc907075f1dccf768d2cc
Change test targets to use _p9 if p9 is enabled. lisafs is default. So we should not have all targets be generated with _lisafs. Also if nothing is specified, then lisafs should run. Which is not the case right now.
[ { "change_type": "MODIFY", "old_path": "test/runner/defs.bzl", "new_path": "test/runner/defs.bzl", "diff": "@@ -84,8 +84,8 @@ def _syscall_test(\nname += \"_overlay\"\nif fuse:\nname += \"_fuse\"\n- if lisafs:\n- name += \"_lisafs\"\n+ if not lisafs:\n+ name += \"_p9\"\nif network != \"none\":\nname += \"_\" + network + \"net\"\n" } ]
Go
Apache License 2.0
google/gvisor
Change test targets to use _p9 if p9 is enabled. lisafs is default. So we should not have all targets be generated with _lisafs. Also if nothing is specified, then lisafs should run. Which is not the case right now. PiperOrigin-RevId: 469770835
259,992
25.08.2022 11:37:38
25,200
df5374fcfa9c46ea52478b7cc3112f125d87d500
Add `runsc usage` to list of commands Also make `runsc debug` write to stdout and log file to make it easier to see the output when running the command manually.
[ { "change_type": "MODIFY", "old_path": "runsc/cli/main.go", "new_path": "runsc/cli/main.go", "diff": "@@ -94,6 +94,7 @@ func Main(version string) {\nsubcommands.Register(new(cmd.Debug), debugGroup)\nsubcommands.Register(new(cmd.Statefile), debugGroup)\nsubcommands.Register(new(cmd.Symbolize), debugGroup)\n+ subcommands.Register(new(cmd.Usage), debugGroup)\n// Internal commands.\nconst internalGroup = \"internal use only\"\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/debug.go", "new_path": "runsc/cmd/debug.go", "diff": "@@ -140,23 +140,23 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nif !c.IsSandboxRunning() {\nreturn util.Errorf(\"container sandbox is not running\")\n}\n- log.Infof(\"Found sandbox %q, PID: %d\", c.Sandbox.ID, c.Sandbox.Getpid())\n+ util.Infof(\"Found sandbox %q, PID: %d\", c.Sandbox.ID, c.Sandbox.Getpid())\n// Perform synchronous actions.\nif d.signal > 0 {\npid := c.Sandbox.Getpid()\n- log.Infof(\"Sending signal %d to process: %d\", d.signal, pid)\n+ util.Infof(\"Sending signal %d to process: %d\", d.signal, pid)\nif err := unix.Kill(pid, unix.Signal(d.signal)); err != nil {\nreturn util.Errorf(\"failed to send signal %d to processs %d\", d.signal, pid)\n}\n}\nif d.stacks {\n- log.Infof(\"Retrieving sandbox stacks\")\n+ util.Infof(\"Retrieving sandbox stacks\")\nstacks, err := c.Sandbox.Stacks()\nif err != nil {\nreturn util.Errorf(\"retrieving stacks: %v\", err)\n}\n- log.Infof(\" *** Stack dump ***\\n%s\", stacks)\n+ util.Infof(\" *** Stack dump ***\\n%s\", stacks)\n}\nif d.strace != \"\" || len(d.logLevel) != 0 || len(d.logPackets) != 0 {\nargs := control.LoggingArgs{}\n@@ -165,16 +165,16 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n// strace not set, nothing to do here.\ncase \"off\":\n- log.Infof(\"Disabling strace\")\n+ util.Infof(\"Disabling strace\")\nargs.SetStrace = true\ncase \"all\":\n- log.Infof(\"Enabling all straces\")\n+ util.Infof(\"Enabling all straces\")\nargs.SetStrace = true\nargs.EnableStrace = true\ndefault:\n- log.Infof(\"Enabling strace for syscalls: %s\", d.strace)\n+ util.Infof(\"Enabling strace for syscalls: %s\", d.strace)\nargs.SetStrace = true\nargs.EnableStrace = true\nargs.StraceAllowlist = strings.Split(d.strace, \",\")\n@@ -192,7 +192,7 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\ndefault:\nreturn util.Errorf(\"invalid log level %q\", d.logLevel)\n}\n- log.Infof(\"Setting log level %v\", args.Level)\n+ util.Infof(\"Setting log level %v\", args.Level)\n}\nif len(d.logPackets) != 0 {\n@@ -203,18 +203,19 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n}\nargs.LogPackets = lp\nif args.LogPackets {\n- log.Infof(\"Enabling packet logging\")\n+ util.Infof(\"Enabling packet logging\")\n} else {\n- log.Infof(\"Disabling packet logging\")\n+ util.Infof(\"Disabling packet logging\")\n}\n}\nif err := c.Sandbox.ChangeLogging(args); err != nil {\nreturn util.Errorf(err.Error())\n}\n- log.Infof(\"Logging options changed\")\n+ util.Infof(\"Logging options changed\")\n}\nif d.ps {\n+ util.Infof(\"Retrieving process list\")\npList, err := c.Processes()\nif err != nil {\nutil.Fatalf(\"getting processes for container: %v\", err)\n@@ -223,7 +224,7 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nif err != nil {\nutil.Fatalf(\"generating JSON: %v\", err)\n}\n- log.Infof(o)\n+ util.Infof(\"%s\", o)\n}\n// Open profiling files.\n@@ -333,13 +334,13 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\ncase <-readyChan:\nbreak // Safe to proceed.\ncase <-signals:\n- log.Infof(\"caught signal, waiting at most one more second.\")\n+ util.Infof(\"caught signal, waiting at most one more second.\")\nselect {\ncase <-signals:\n- log.Infof(\"caught second signal, exiting immediately.\")\n+ util.Infof(\"caught second signal, exiting immediately.\")\nos.Exit(1) // Not finished.\ncase <-time.After(time.Second):\n- log.Infof(\"timeout, exiting.\")\n+ util.Infof(\"timeout, exiting.\")\nos.Exit(1) // Not finished.\ncase <-readyChan:\nbreak // Safe to proceed.\n@@ -350,27 +351,27 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nerrorCount := 0\nif blockErr != nil {\nerrorCount++\n- log.Infof(\"error collecting block profile: %v\", blockErr)\n+ util.Infof(\"error collecting block profile: %v\", blockErr)\nos.Remove(blockFile.Name())\n}\nif cpuErr != nil {\nerrorCount++\n- log.Infof(\"error collecting cpu profile: %v\", cpuErr)\n+ util.Infof(\"error collecting cpu profile: %v\", cpuErr)\nos.Remove(cpuFile.Name())\n}\nif heapErr != nil {\nerrorCount++\n- log.Infof(\"error collecting heap profile: %v\", heapErr)\n+ util.Infof(\"error collecting heap profile: %v\", heapErr)\nos.Remove(heapFile.Name())\n}\nif mutexErr != nil {\nerrorCount++\n- log.Infof(\"error collecting mutex profile: %v\", mutexErr)\n+ util.Infof(\"error collecting mutex profile: %v\", mutexErr)\nos.Remove(mutexFile.Name())\n}\nif traceErr != nil {\nerrorCount++\n- log.Infof(\"error collecting trace profile: %v\", traceErr)\n+ util.Infof(\"error collecting trace profile: %v\", traceErr)\nos.Remove(traceFile.Name())\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/events.go", "new_path": "runsc/cmd/events.go", "diff": "@@ -72,7 +72,7 @@ func (evs *Events) SetFlags(f *flag.FlagSet) {\n}\n// Execute implements subcommands.Command.Execute.\n-func (evs *Events) Execute(ctx context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {\n+func (evs *Events) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {\nif f.NArg() != 1 {\nf.Usage()\nreturn subcommands.ExitUsageError\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/usage.go", "new_path": "runsc/cmd/usage.go", "diff": "@@ -17,8 +17,6 @@ package cmd\nimport (\n\"context\"\n\"encoding/json\"\n- \"fmt\"\n- \"os\"\n\"github.com/google/subcommands\"\n\"gvisor.dev/gvisor/runsc/cmd/util\"\n@@ -69,16 +67,8 @@ func (u *Usage) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nutil.Fatalf(\"loading container: %v\", err)\n}\n- if !u.fd {\n- m, err := cont.Usage(u.full)\n- if err != nil {\n- util.Fatalf(\"usage failed: %v\", err)\n- }\n- if err := json.NewEncoder(os.Stdout).Encode(m); err != nil {\n- util.Fatalf(\"Encode MemoryUsage failed: %v\", err)\n- }\n- } else {\n- m, err := cont.UsageFD()\n+ if u.fd {\n+ m, err := cont.Sandbox.UsageFD()\nif err != nil {\nutil.Fatalf(\"usagefd failed: %v\", err)\n}\n@@ -88,7 +78,17 @@ func (u *Usage) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nutil.Fatalf(\"Fetch memory usage failed: %v\", err)\n}\n- fmt.Printf(\"Mapped %v, Unknown %v, Total %v\\n\", mapped, unknown, total)\n+ util.Infof(\"Mapped %v, Unknown %v, Total %v\\n\", mapped, unknown, total)\n+ } else {\n+ m, err := cont.Sandbox.Usage(u.full)\n+ if err != nil {\n+ util.Fatalf(\"usage failed: %v\", err)\n+ }\n+ encoder := json.NewEncoder(&util.Writer{})\n+ encoder.SetIndent(\"\", \" \")\n+ if err := encoder.Encode(m); err != nil {\n+ util.Fatalf(\"Encode MemoryUsage failed: %v\", err)\n+ }\n}\nreturn subcommands.ExitSuccess\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/util/util.go", "new_path": "runsc/cmd/util/util.go", "diff": "@@ -37,6 +37,21 @@ type jsonError struct {\nTime time.Time `json:\"time\"`\n}\n+// Writer writes to log and stdout.\n+type Writer struct{}\n+\n+// Write implements io.Writer.\n+func (i *Writer) Write(data []byte) (n int, err error) {\n+ log.Infof(\"%s\", data)\n+ return os.Stdout.Write(data)\n+}\n+\n+// Infof writes message to log and stdout.\n+func Infof(format string, args ...interface{}) {\n+ log.Infof(format, args)\n+ fmt.Printf(format+\"\\n\", args)\n+}\n+\n// Errorf logs error to containerd log (--log), to stderr, and debug logs. It\n// returns subcommands.ExitFailure for convenience with subcommand.Execute()\n// methods:\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container.go", "new_path": "runsc/container/container.go", "diff": "@@ -678,24 +678,6 @@ func (c *Container) Cat(files []string, out *os.File) error {\nreturn c.Sandbox.Cat(c.ID, files, out)\n}\n-// Usage displays memory used by the application.\n-func (c *Container) Usage(full bool) (control.MemoryUsage, error) {\n- log.Debugf(\"Usage in container, cid: %s, full: %v\", c.ID, full)\n- return c.Sandbox.Usage(c.ID, full)\n-}\n-\n-// UsageFD shows application memory usage using two donated FDs.\n-func (c *Container) UsageFD() (*control.MemoryUsageRecord, error) {\n- log.Debugf(\"UsageFD in container, cid: %s\", c.ID)\n- return c.Sandbox.UsageFD(c.ID)\n-}\n-\n-// Reduce requests that the sentry attempt to reduce its memory usage.\n-func (c *Container) Reduce(wait bool) error {\n- log.Debugf(\"Reduce in container, cid: %s\", c.ID)\n- return c.Sandbox.Reduce(c.ID, wait)\n-}\n-\n// Stream dumps all events to out.\nfunc (c *Container) Stream(filters []string, out *os.File) error {\nlog.Debugf(\"Stream in container, cid: %s\", c.ID)\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container_test.go", "new_path": "runsc/container/container_test.go", "diff": "@@ -2590,7 +2590,7 @@ func TestUsage(t *testing.T) {\n}\nfor _, full := range []bool{false, true} {\n- m, err := cont.Usage(full)\n+ m, err := cont.Sandbox.Usage(full)\nif err != nil {\nt.Fatalf(\"error usage from container: %v\", err)\n}\n@@ -2637,7 +2637,7 @@ func TestUsageFD(t *testing.T) {\nt.Fatalf(\"starting container: %v\", err)\n}\n- m, err := cont.UsageFD()\n+ m, err := cont.Sandbox.UsageFD()\nif err != nil {\nt.Fatalf(\"error usageFD from container: %v\", err)\n}\n@@ -2683,7 +2683,7 @@ func TestReduce(t *testing.T) {\nt.Fatalf(\"starting container: %v\", err)\n}\n- if err := cont.Reduce(false); err != nil {\n+ if err := cont.Sandbox.Reduce(false); err != nil {\nt.Fatalf(\"error reduce from container: %v\", err)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/sandbox.go", "new_path": "runsc/sandbox/sandbox.go", "diff": "@@ -1140,7 +1140,7 @@ func (s *Sandbox) Cat(cid string, files []string, out *os.File) error {\n}\n// Usage sends the collect call for a container in the sandbox.\n-func (s *Sandbox) Usage(cid string, Full bool) (control.MemoryUsage, error) {\n+func (s *Sandbox) Usage(Full bool) (control.MemoryUsage, error) {\nlog.Debugf(\"Usage sandbox %q\", s.ID)\nconn, err := s.sandboxConnect()\nif err != nil {\n@@ -1156,7 +1156,7 @@ func (s *Sandbox) Usage(cid string, Full bool) (control.MemoryUsage, error) {\n}\n// UsageFD sends the usagefd call for a container in the sandbox.\n-func (s *Sandbox) UsageFD(cid string) (*control.MemoryUsageRecord, error) {\n+func (s *Sandbox) UsageFD() (*control.MemoryUsageRecord, error) {\nlog.Debugf(\"Usage sandbox %q\", s.ID)\nconn, err := s.sandboxConnect()\nif err != nil {\n@@ -1179,7 +1179,7 @@ func (s *Sandbox) UsageFD(cid string) (*control.MemoryUsageRecord, error) {\n}\n// Reduce sends the reduce call for a container in the sandbox.\n-func (s *Sandbox) Reduce(cid string, wait bool) error {\n+func (s *Sandbox) Reduce(wait bool) error {\nlog.Debugf(\"Reduce sandbox %q\", s.ID)\nconn, err := s.sandboxConnect()\nif err != nil {\n" }, { "change_type": "MODIFY", "old_path": "test/runner/main.go", "new_path": "test/runner/main.go", "diff": "@@ -287,7 +287,7 @@ func runRunsc(tc gtest.TestCase, spec *specs.Spec) error {\nlog.Warningf(\"%s: Got signal: %v\", name, s)\ndone := make(chan bool, 1)\ndArgs := append([]string{}, args...)\n- dArgs = append(dArgs, \"-alsologtostderr=true\", \"debug\", \"--stacks\", id)\n+ dArgs = append(dArgs, \"debug\", \"--stacks\", id)\ngo func(dArgs []string) {\ndebug := exec.Command(specutils.ExePath, dArgs...)\ndebug.Stdout = os.Stdout\n" } ]
Go
Apache License 2.0
google/gvisor
Add `runsc usage` to list of commands Also make `runsc debug` write to stdout and log file to make it easier to see the output when running the command manually. PiperOrigin-RevId: 470042053
259,992
25.08.2022 14:13:03
25,200
385afe9f2cc43c740221543b739ec6d32c925039
Remove unused runsc flags
[ { "change_type": "MODIFY", "old_path": "runsc/boot/BUILD", "new_path": "runsc/boot/BUILD", "diff": "@@ -48,7 +48,6 @@ go_library(\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/arch:registers_go_proto\",\n\"//pkg/sentry/control\",\n- \"//pkg/sentry/control:control_go_proto\",\n\"//pkg/sentry/devices/memdev\",\n\"//pkg/sentry/devices/ttydev\",\n\"//pkg/sentry/devices/tundev\",\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/controller.go", "new_path": "runsc/boot/controller.go", "diff": "@@ -26,7 +26,6 @@ import (\n\"gvisor.dev/gvisor/pkg/fd\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/control\"\n- controlpb \"gvisor.dev/gvisor/pkg/sentry/control/control_go_proto\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/netstack\"\n@@ -123,11 +122,6 @@ const (\nLifecycleResume = \"Lifecycle.Resume\"\n)\n-// Filesystem related commands (see fs.go for more details).\n-const (\n- FsCat = \"Fs.Cat\"\n-)\n-\n// Usage related commands (see usage.go for more details).\nconst (\nUsageCollect = \"Usage.Collect\"\n@@ -135,11 +129,6 @@ const (\nUsageReduce = \"Usage.Reduce\"\n)\n-// Events related commands (see events.go for more details).\n-const (\n- EventsAttachDebugEmitter = \"Events.AttachDebugEmitter\"\n-)\n-\n// ControlSocketAddr generates an abstract unix socket name for the given ID.\nfunc ControlSocketAddr(id string) string {\nreturn fmt.Sprintf(\"\\x00runsc-sandbox.%s\", id)\n@@ -158,54 +147,33 @@ type controller struct {\n// newController creates a new controller. The caller must call\n// controller.srv.StartServing() to start the controller.\nfunc newController(fd int, l *Loader) (*controller, error) {\n- ctrl := &controller{}\n- var err error\n- ctrl.srv, err = server.CreateFromFD(fd)\n+ srv, err := server.CreateFromFD(fd)\nif err != nil {\nreturn nil, err\n}\n- ctrl.manager = &containerManager{\n+ ctrl := &controller{\n+ manager: &containerManager{\nstartChan: make(chan struct{}),\nstartResultChan: make(chan error),\nl: l,\n+ },\n+ srv: srv,\n}\nctrl.srv.Register(ctrl.manager)\n-\n- if eps, ok := l.k.RootNetworkNamespace().Stack().(*netstack.Stack); ok {\n- net := &Network{\n- Stack: eps.Stack,\n- }\n- ctrl.srv.Register(net)\n- }\n-\n- if l.root.conf.Controls.Controls != nil {\n- for _, c := range l.root.conf.Controls.Controls.AllowedControls {\n- switch c {\n- case controlpb.ControlConfig_EVENTS:\n- ctrl.srv.Register(&control.Events{})\n- case controlpb.ControlConfig_FS:\n- ctrl.srv.Register(&control.Fs{Kernel: l.k})\n- case controlpb.ControlConfig_LIFECYCLE:\nctrl.srv.Register(&control.Lifecycle{Kernel: l.k})\n- case controlpb.ControlConfig_LOGGING:\nctrl.srv.Register(&control.Logging{})\n- case controlpb.ControlConfig_PROFILE:\n- if l.root.conf.ProfileEnable {\n- ctrl.srv.Register(control.NewProfile(l.k))\n- }\n- case controlpb.ControlConfig_USAGE:\n- ctrl.srv.Register(&control.Usage{Kernel: l.k})\n- case controlpb.ControlConfig_PROC:\nctrl.srv.Register(&control.Proc{Kernel: l.k})\n- case controlpb.ControlConfig_STATE:\nctrl.srv.Register(&control.State{Kernel: l.k})\n- case controlpb.ControlConfig_DEBUG:\n+ ctrl.srv.Register(&control.Usage{Kernel: l.k})\nctrl.srv.Register(&debug{})\n+\n+ if eps, ok := l.k.RootNetworkNamespace().Stack().(*netstack.Stack); ok {\n+ ctrl.srv.Register(&Network{Stack: eps.Stack})\n}\n+ if l.root.conf.ProfileEnable {\n+ ctrl.srv.Register(control.NewProfile(l.k))\n}\n- }\n-\nreturn ctrl, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/debug.go", "new_path": "runsc/cmd/debug.go", "diff": "@@ -49,7 +49,6 @@ type Debug struct {\ndelay time.Duration\nduration time.Duration\nps bool\n- cat stringSlice\n}\n// Name implements subcommands.Command.\n@@ -83,7 +82,6 @@ func (d *Debug) SetFlags(f *flag.FlagSet) {\nf.StringVar(&d.logLevel, \"log-level\", \"\", \"The log level to set: warning (0), info (1), or debug (2).\")\nf.StringVar(&d.logPackets, \"log-packets\", \"\", \"A boolean value to enable or disable packet logging: true or false.\")\nf.BoolVar(&d.ps, \"ps\", false, \"lists processes\")\n- f.Var(&d.cat, \"cat\", \"reads files and print to standard output\")\n}\n// Execute implements subcommands.Command.Execute.\n@@ -379,11 +377,5 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nreturn subcommands.ExitFailure\n}\n- if d.cat != nil {\n- if err := c.Cat(d.cat, os.Stdout); err != nil {\n- return util.Errorf(\"Cat failed: %v\", err)\n- }\n- }\n-\nreturn subcommands.ExitSuccess\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/events.go", "new_path": "runsc/cmd/events.go", "diff": "@@ -34,10 +34,6 @@ type Events struct {\nintervalSec int\n// If true, events will print a single group of stats and exit.\nstats bool\n- // If true, events will dump all filtered events to stdout.\n- stream bool\n- // filters for streamed events.\n- filters stringSlice\n}\n// Name implements subcommands.Command.Name.\n@@ -67,8 +63,6 @@ OPTIONS:\nfunc (evs *Events) SetFlags(f *flag.FlagSet) {\nf.IntVar(&evs.intervalSec, \"interval\", 5, \"set the stats collection interval, in seconds\")\nf.BoolVar(&evs.stats, \"stats\", false, \"display the container's stats then exit\")\n- f.BoolVar(&evs.stream, \"stream\", false, \"dump all filtered events to stdout\")\n- f.Var(&evs.filters, \"filters\", \"only display matching events\")\n}\n// Execute implements subcommands.Command.Execute.\n@@ -86,15 +80,9 @@ func (evs *Events) Execute(_ context.Context, f *flag.FlagSet, args ...interface\nutil.Fatalf(\"loading sandbox: %v\", err)\n}\n- if evs.stream {\n- if err := c.Stream(evs.filters, os.Stdout); err != nil {\n- util.Fatalf(\"Stream failed: %v\", err)\n- }\n- return subcommands.ExitSuccess\n- }\n-\n- // Repeatedly get stats from the container.\n- for {\n+ // Repeatedly get stats from the container. Sleep a bit after every loop\n+ // except the first one.\n+ for dur := time.Duration(evs.intervalSec) * time.Second; true; time.Sleep(dur) {\n// Get the event and print it as JSON.\nev, err := c.Event()\nif err != nil {\n@@ -102,29 +90,22 @@ func (evs *Events) Execute(_ context.Context, f *flag.FlagSet, args ...interface\nif evs.stats {\nreturn subcommands.ExitFailure\n}\n+ continue\n}\nlog.Debugf(\"Events: %+v\", ev)\n- // err must be preserved because it is used below when breaking\n- // out of the loop.\n- b, err := json.Marshal(ev.Event)\n- if err != nil {\n- log.Warningf(\"Error while marshalling event %v: %v\", ev.Event, err)\n- } else {\n- if _, err := os.Stdout.Write(b); err != nil {\n- util.Fatalf(\"Error writing to stdout: %v\", err)\n+ if err := json.NewEncoder(os.Stdout).Encode(ev.Event); err != nil {\n+ log.Warningf(\"Error encoding event %+v: %v\", ev.Event, err)\n+ if evs.stats {\n+ return subcommands.ExitFailure\n}\n+ continue\n}\n- // If we're only running once, break. If we're only running\n- // once and there was an error, the command failed.\n+ // Break if we're only running once. If we got this far it was a success.\nif evs.stats {\n- if err != nil {\n- return subcommands.ExitFailure\n- }\nreturn subcommands.ExitSuccess\n}\n-\n- time.Sleep(time.Duration(evs.intervalSec) * time.Second)\n}\n+ panic(\"should never get here\")\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/BUILD", "new_path": "runsc/config/BUILD", "diff": "@@ -11,7 +11,6 @@ go_library(\nvisibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/refs\",\n- \"//pkg/sentry/control:control_go_proto\",\n\"//pkg/sentry/watchdog\",\n\"//runsc/flag\",\n],\n@@ -24,8 +23,5 @@ go_test(\n\"config_test.go\",\n],\nlibrary = \":config\",\n- deps = [\n- \"//pkg/sentry/control:control_go_proto\",\n- \"//runsc/flag\",\n- ],\n+ deps = [\"//runsc/flag\"],\n)\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/config.go", "new_path": "runsc/config/config.go", "diff": "@@ -19,10 +19,8 @@ package config\nimport (\n\"fmt\"\n- \"strings\"\n\"gvisor.dev/gvisor/pkg/refs\"\n- controlpb \"gvisor.dev/gvisor/pkg/sentry/control/control_go_proto\"\n\"gvisor.dev/gvisor/pkg/sentry/watchdog\"\n)\n@@ -172,9 +170,6 @@ type Config struct {\n// for the duration of the container execution.\nTraceFile string `flag:\"trace\"`\n- // Controls defines the controls that may be enabled.\n- Controls controlConfig `flag:\"controls\"`\n-\n// RestoreFile is the path to the saved container image.\nRestoreFile string\n@@ -428,96 +423,6 @@ func (q QueueingDiscipline) String() string {\npanic(fmt.Sprintf(\"Invalid qdisc %d\", q))\n}\n-// controlConfig represents control endpoints.\n-type controlConfig struct {\n- Controls *controlpb.ControlConfig\n-}\n-\n-// Set implements flag.Value.\n-func (c *controlConfig) Set(v string) error {\n- controls := strings.Split(v, \",\")\n- var controlList []controlpb.ControlConfig_Endpoint\n- for _, control := range controls {\n- switch control {\n- case \"EVENTS\":\n- controlList = append(controlList, controlpb.ControlConfig_EVENTS)\n- case \"FS\":\n- controlList = append(controlList, controlpb.ControlConfig_FS)\n- case \"LIFECYCLE\":\n- controlList = append(controlList, controlpb.ControlConfig_LIFECYCLE)\n- case \"LOGGING\":\n- controlList = append(controlList, controlpb.ControlConfig_LOGGING)\n- case \"PROFILE\":\n- controlList = append(controlList, controlpb.ControlConfig_PROFILE)\n- case \"USAGE\":\n- controlList = append(controlList, controlpb.ControlConfig_USAGE)\n- case \"PROC\":\n- controlList = append(controlList, controlpb.ControlConfig_PROC)\n- case \"STATE\":\n- controlList = append(controlList, controlpb.ControlConfig_STATE)\n- case \"DEBUG\":\n- controlList = append(controlList, controlpb.ControlConfig_DEBUG)\n- default:\n- return fmt.Errorf(\"invalid control %q\", control)\n- }\n- }\n- c.Controls.AllowedControls = controlList\n- return nil\n-}\n-\n-// Get implements flag.Value.\n-func (c *controlConfig) Get() interface{} {\n- return *c\n-}\n-\n-// String implements flag.Value.\n-func (c *controlConfig) String() string {\n- v := \"\"\n- for _, control := range c.Controls.GetAllowedControls() {\n- if len(v) > 0 {\n- v += \",\"\n- }\n- switch control {\n- case controlpb.ControlConfig_EVENTS:\n- v += \"EVENTS\"\n- case controlpb.ControlConfig_FS:\n- v += \"FS\"\n- case controlpb.ControlConfig_LIFECYCLE:\n- v += \"LIFECYCLE\"\n- case controlpb.ControlConfig_LOGGING:\n- v += \"LOGGING\"\n- case controlpb.ControlConfig_PROFILE:\n- v += \"PROFILE\"\n- case controlpb.ControlConfig_USAGE:\n- v += \"USAGE\"\n- case controlpb.ControlConfig_PROC:\n- v += \"PROC\"\n- case controlpb.ControlConfig_STATE:\n- v += \"STATE\"\n- case controlpb.ControlConfig_DEBUG:\n- v += \"DEBUG\"\n- default:\n- panic(fmt.Sprintf(\"Invalid control %d\", control))\n- }\n- }\n- return v\n-}\n-\n-func defaultControlConfig() *controlConfig {\n- c := controlConfig{}\n- c.Controls = &controlpb.ControlConfig{}\n- c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_EVENTS)\n- c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_FS)\n- c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_LIFECYCLE)\n- c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_LOGGING)\n- c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_PROFILE)\n- c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_USAGE)\n- c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_PROC)\n- c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_STATE)\n- c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_DEBUG)\n- return &c\n-}\n-\nfunc leakModePtr(v refs.LeakMode) *refs.LeakMode {\nreturn &v\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/config_test.go", "new_path": "runsc/config/config_test.go", "diff": "@@ -18,7 +18,6 @@ import (\n\"strings\"\n\"testing\"\n- controlpb \"gvisor.dev/gvisor/pkg/sentry/control/control_go_proto\"\n\"gvisor.dev/gvisor/runsc/flag\"\n)\n@@ -55,9 +54,6 @@ func TestFromFlags(t *testing.T) {\nif err := testFlags.Lookup(\"network\").Value.Set(\"none\"); err != nil {\nt.Errorf(\"Flag set: %v\", err)\n}\n- if err := testFlags.Lookup(\"controls\").Value.Set(\"EVENTS,FS\"); err != nil {\n- t.Errorf(\"Flag set: %v\", err)\n- }\nc, err := NewFromFlags(testFlags)\nif err != nil {\n@@ -75,12 +71,6 @@ func TestFromFlags(t *testing.T) {\nif want := NetworkNone; c.Network != want {\nt.Errorf(\"Network=%v, want: %v\", c.Network, want)\n}\n- wants := []controlpb.ControlConfig_Endpoint{controlpb.ControlConfig_EVENTS, controlpb.ControlConfig_FS}\n- for i, want := range wants {\n- if c.Controls.Controls.AllowedControls[i] != want {\n- t.Errorf(\"Controls.Controls.AllowedControls[%d]=%v, want: %v\", i, c.Controls.Controls.AllowedControls[i], want)\n- }\n- }\n}\nfunc TestToFlags(t *testing.T) {\n@@ -94,14 +84,9 @@ func TestToFlags(t *testing.T) {\nc.Debug = true\nc.NumNetworkChannels = 123\nc.Network = NetworkNone\n- c.Controls = controlConfig{\n- Controls: &controlpb.ControlConfig{\n- AllowedControls: []controlpb.ControlConfig_Endpoint{controlpb.ControlConfig_EVENTS, controlpb.ControlConfig_FS},\n- },\n- }\nflags := c.ToFlags()\n- if len(flags) != 5 {\n+ if len(flags) != 4 {\nt.Errorf(\"wrong number of flags set, want: 5, got: %d: %s\", len(flags), flags)\n}\nt.Logf(\"Flags: %s\", flags)\n@@ -115,7 +100,6 @@ func TestToFlags(t *testing.T) {\n\"--debug\": \"true\",\n\"--num-network-channels\": \"123\",\n\"--network\": \"none\",\n- \"--controls\": \"EVENTS,FS\",\n} {\nif got, ok := fm[name]; ok {\nif got != want {\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/flags.go", "new_path": "runsc/config/flags.go", "diff": "@@ -70,7 +70,6 @@ func RegisterFlags(flagSet *flag.FlagSet) {\nflagSet.Var(leakModePtr(refs.NoLeakChecking), \"ref-leak-mode\", \"sets reference leak check mode: disabled (default), log-names, log-traces.\")\nflagSet.Bool(\"cpu-num-from-quota\", false, \"set cpu number to cpu quota (least integer greater or equal to quota value, but not less than 2)\")\nflagSet.Bool(\"oci-seccomp\", false, \"Enables loading OCI seccomp filters inside the sandbox.\")\n- flagSet.Var(defaultControlConfig(), \"controls\", \"Sentry control endpoints.\")\nflagSet.Bool(\"enable-core-tags\", false, \"enables core tagging. Requires host linux kernel >= 5.14.\")\nflagSet.String(\"pod-init-config\", \"\", \"path to configuration file with additional steps to take during pod creation.\")\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container.go", "new_path": "runsc/container/container.go", "diff": "@@ -672,18 +672,6 @@ func (c *Container) Resume() error {\nreturn c.saveLocked()\n}\n-// Cat prints out the content of the files.\n-func (c *Container) Cat(files []string, out *os.File) error {\n- log.Debugf(\"Cat in container, cid: %s, files: %+v\", c.ID, files)\n- return c.Sandbox.Cat(c.ID, files, out)\n-}\n-\n-// Stream dumps all events to out.\n-func (c *Container) Stream(filters []string, out *os.File) error {\n- log.Debugf(\"Stream in container, cid: %s\", c.ID)\n- return c.Sandbox.Stream(c.ID, filters, out)\n-}\n-\n// State returns the metadata of the container.\nfunc (c *Container) State() specs.State {\nreturn specs.State{\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container_test.go", "new_path": "runsc/container/container_test.go", "diff": "@@ -2509,61 +2509,6 @@ func TestRlimitsExec(t *testing.T) {\n}\n}\n-// TestCat creates a file and checks that cat generates the expected output.\n-func TestCat(t *testing.T) {\n- f, err := ioutil.TempFile(testutil.TmpDir(), \"test-case\")\n- if err != nil {\n- t.Fatalf(\"ioutil.TempFile failed: %v\", err)\n- }\n- defer os.RemoveAll(f.Name())\n-\n- content := \"test-cat\"\n- if _, err := f.WriteString(content); err != nil {\n- t.Fatalf(\"f.WriteString(): %v\", err)\n- }\n- f.Close()\n-\n- spec, conf := sleepSpecConf(t)\n- _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\n- if err != nil {\n- t.Fatalf(\"error setting up container: %v\", err)\n- }\n- defer cleanup()\n-\n- args := Args{\n- ID: testutil.RandomContainerID(),\n- Spec: spec,\n- BundleDir: bundleDir,\n- }\n-\n- cont, err := New(conf, args)\n- if err != nil {\n- t.Fatalf(\"Creating container: %v\", err)\n- }\n- defer cont.Destroy()\n-\n- if err := cont.Start(conf); err != nil {\n- t.Fatalf(\"starting container: %v\", err)\n- }\n-\n- r, w, err := os.Pipe()\n- if err != nil {\n- t.Fatalf(\"os.Create(): %v\", err)\n- }\n-\n- if err := cont.Cat([]string{f.Name()}, w); err != nil {\n- t.Fatalf(\"error cat from container: %v\", err)\n- }\n-\n- buf := make([]byte, 1024)\n- if _, err := r.Read(buf); err != nil {\n- t.Fatalf(\"Read out: %v\", err)\n- }\n- if got, want := string(buf), content; !strings.Contains(got, want) {\n- t.Errorf(\"out got %s, want include %s\", buf, want)\n- }\n-}\n-\n// TestUsage checks that usage generates the expected memory usage.\nfunc TestUsage(t *testing.T) {\nspec, conf := sleepSpecConf(t)\n@@ -2688,56 +2633,6 @@ func TestReduce(t *testing.T) {\n}\n}\n-// TestStream checks that Stream dumps expected events.\n-func TestStream(t *testing.T) {\n- spec, conf := sleepSpecConf(t)\n- conf.Strace = true\n- conf.StraceEvent = true\n- conf.StraceSyscalls = \"\"\n-\n- _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\n- if err != nil {\n- t.Fatalf(\"error setting up container: %v\", err)\n- }\n- defer cleanup()\n-\n- args := Args{\n- ID: testutil.RandomContainerID(),\n- Spec: spec,\n- BundleDir: bundleDir,\n- }\n-\n- cont, err := New(conf, args)\n- if err != nil {\n- t.Fatalf(\"Creating container: %v\", err)\n- }\n- defer cont.Destroy()\n-\n- if err := cont.Start(conf); err != nil {\n- t.Fatalf(\"starting container: %v\", err)\n- }\n-\n- r, w, err := os.Pipe()\n- if err != nil {\n- t.Fatalf(\"os.Create(): %v\", err)\n- }\n-\n- // Spawn a new thread to Stream events as it blocks indefinitely.\n- go func() {\n- cont.Stream(nil, w)\n- }()\n-\n- buf := make([]byte, 1024)\n- if _, err := r.Read(buf); err != nil {\n- t.Fatalf(\"Read out: %v\", err)\n- }\n-\n- // A syscall strace event includes \"Strace\".\n- if got, want := string(buf), \"Strace\"; !strings.Contains(got, want) {\n- t.Errorf(\"out got %s, want include %s\", buf, want)\n- }\n-}\n-\n// TestProfile checks that profiling options generate profiles.\nfunc TestProfile(t *testing.T) {\n// Perform a non-trivial amount of work so we actually capture\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/BUILD", "new_path": "runsc/sandbox/BUILD", "diff": "@@ -19,7 +19,6 @@ go_library(\n\"//pkg/control/client\",\n\"//pkg/control/server\",\n\"//pkg/coverage\",\n- \"//pkg/eventchannel\",\n\"//pkg/log\",\n\"//pkg/sentry/control\",\n\"//pkg/sentry/platform\",\n@@ -27,7 +26,6 @@ go_library(\n\"//pkg/sync\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/stack\",\n- \"//pkg/unet\",\n\"//pkg/urpc\",\n\"//runsc/boot\",\n\"//runsc/boot/procfs\",\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/sandbox.go", "new_path": "runsc/sandbox/sandbox.go", "diff": "@@ -38,13 +38,11 @@ import (\n\"gvisor.dev/gvisor/pkg/control/client\"\n\"gvisor.dev/gvisor/pkg/control/server\"\n\"gvisor.dev/gvisor/pkg/coverage\"\n- \"gvisor.dev/gvisor/pkg/eventchannel\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/control\"\n\"gvisor.dev/gvisor/pkg/sentry/platform\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck\"\n\"gvisor.dev/gvisor/pkg/sync\"\n- \"gvisor.dev/gvisor/pkg/unet\"\n\"gvisor.dev/gvisor/pkg/urpc\"\n\"gvisor.dev/gvisor/runsc/boot\"\n\"gvisor.dev/gvisor/runsc/boot/procfs\"\n@@ -1121,24 +1119,6 @@ func (s *Sandbox) Resume(cid string) error {\nreturn nil\n}\n-// Cat sends the cat call for a container in the sandbox.\n-func (s *Sandbox) Cat(cid string, files []string, out *os.File) error {\n- log.Debugf(\"Cat sandbox %q\", s.ID)\n- conn, err := s.sandboxConnect()\n- if err != nil {\n- return err\n- }\n- defer conn.Close()\n-\n- if err := conn.Call(boot.FsCat, &control.CatOpts{\n- Files: files,\n- FilePayload: urpc.FilePayload{Files: []*os.File{out}},\n- }, nil); err != nil {\n- return fmt.Errorf(\"Cat container %q: %v\", cid, err)\n- }\n- return nil\n-}\n-\n// Usage sends the collect call for a container in the sandbox.\nfunc (s *Sandbox) Usage(Full bool) (control.MemoryUsage, error) {\nlog.Debugf(\"Usage sandbox %q\", s.ID)\n@@ -1192,37 +1172,6 @@ func (s *Sandbox) Reduce(wait bool) error {\n}, nil)\n}\n-// Stream sends the AttachDebugEmitter call for a container in the sandbox, and\n-// dumps filtered events to out.\n-func (s *Sandbox) Stream(cid string, filters []string, out *os.File) error {\n- log.Debugf(\"Stream sandbox %q\", s.ID)\n- conn, err := s.sandboxConnect()\n- if err != nil {\n- return err\n- }\n- defer conn.Close()\n-\n- r, w, err := unet.SocketPair(false)\n- if err != nil {\n- return err\n- }\n-\n- wfd, err := w.Release()\n- if err != nil {\n- return fmt.Errorf(\"failed to release write socket FD: %v\", err)\n- }\n-\n- if err := conn.Call(boot.EventsAttachDebugEmitter, &control.EventsOpts{\n- FilePayload: urpc.FilePayload{Files: []*os.File{\n- os.NewFile(uintptr(wfd), \"event sink\"),\n- }},\n- }, nil); err != nil {\n- return fmt.Errorf(\"AttachDebugEmitter failed: %v\", err)\n- }\n-\n- return eventchannel.ProcessAll(r, filters, out)\n-}\n-\n// IsRunning returns true if the sandbox or gofer process is running.\nfunc (s *Sandbox) IsRunning() bool {\npid := s.Pid.load()\n" } ]
Go
Apache License 2.0
google/gvisor
Remove unused runsc flags PiperOrigin-RevId: 470080145
259,891
25.08.2022 16:21:15
25,200
540c79c8cf7ddbf265052c67d1f4f74ed199bb71
netstack: add --EXPERIMENTAL-afxdp flag Setting the flag creates an AF_XDP socket that will be consumed by the XDP dispatcher.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/fdbased/endpoint.go", "new_path": "pkg/tcpip/link/fdbased/endpoint.go", "diff": "package fdbased\nimport (\n+ \"errors\"\n\"fmt\"\n\"golang.org/x/sys/unix\"\n@@ -88,6 +89,9 @@ const (\n// primary use-case for this is runsc which uses an AF_PACKET FD to\n// receive packets from the veth device.\nPacketMMap\n+ // AFXDP utilizes an AF_XDP socket to receive packets. AFXDP requires that\n+ // the underlying FD be an AF_XDP socket.\n+ AFXDP\n)\nfunc (p PacketDispatchMode) String() string {\n@@ -98,6 +102,8 @@ func (p PacketDispatchMode) String() string {\nreturn \"RecvMMsg\"\ncase PacketMMap:\nreturn \"PacketMMap\"\n+ case AFXDP:\n+ return \"AFXDP\"\ndefault:\nreturn fmt.Sprintf(\"unknown packet dispatch mode '%d'\", p)\n}\n@@ -217,6 +223,11 @@ type Options struct {\n// of struct iovec, msghdr, and mmsghdr that may be passed by each host\n// system call.\nMaxSyscallHeaderBytes int\n+\n+ // AFXDPFD is used with the experimental AF_XDP mode.\n+ // TODO(b/240191988): Use multiple sockets.\n+ // TODO(b/240191988): How do we handle the MTU issue?\n+ AFXDPFD int\n}\n// fanoutID is used for AF_PACKET based endpoints to enable PACKET_FANOUT\n@@ -374,6 +385,8 @@ func createInboundDispatcher(e *endpoint, fd int, isSocket bool, fID int32) (lin\nif err != nil {\nreturn nil, fmt.Errorf(\"newRecvMMsgDispatcher(%d, %+v) = %v\", fd, e, err)\n}\n+ case AFXDP:\n+ return nil, errors.New(\"AFXDP not yet implemented\")\n}\n}\nreturn inboundDispatcher, nil\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/network.go", "new_path": "runsc/boot/network.go", "diff": "@@ -99,7 +99,7 @@ type FDBasedLink struct {\nQDisc config.QueueingDiscipline\nNeighbors []Neighbor\n- // NumChannels controls how many underlying FD's are to be used to\n+ // NumChannels controls how many underlying FDs are to be used to\n// create this endpoint.\nNumChannels int\n}\n@@ -123,6 +123,8 @@ type CreateLinksAndRoutesArgs struct {\nDefaultv4Gateway DefaultRoute\nDefaultv6Gateway DefaultRoute\n+\n+ AFXDP bool\n}\n// IPWithPrefix is an address with its subnet prefix length.\n@@ -162,8 +164,11 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\nfor _, l := range args.FDBasedLinks {\nwantFDs += l.NumChannels\n}\n+ if args.AFXDP {\n+ wantFDs++\n+ }\nif got := len(args.FilePayload.Files); got != wantFDs {\n- return fmt.Errorf(\"args.FilePayload.Files has %d FD's but we need %d entries based on FDBasedLinks\", got, wantFDs)\n+ return fmt.Errorf(\"args.FilePayload.Files has %d FDs but we need %d entries based on FDBasedLinks. AFXDP is %t\", got, wantFDs, args.AFXDP)\n}\nvar nicID tcpip.NICID\n@@ -206,13 +211,16 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\n} else {\nlog.Infof(\"Host kernel version < 5.6, falling back to RecvMMsg dispatch\")\n}\n+ if args.AFXDP {\n+ dispatchMode = fdbased.AFXDP\n+ }\nfdOffset := 0\nfor _, link := range args.FDBasedLinks {\nnicID++\nnicids[link.Name] = nicID\n- FDs := []int{}\n+ FDs := make([]int, 0, link.NumChannels)\nfor j := 0; j < link.NumChannels; j++ {\n// Copy the underlying FD.\noldFD := args.FilePayload.Files[fdOffset].Fd()\n@@ -224,11 +232,25 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\nfdOffset++\n}\n+ // If AFXDP is enabled, we perform RX via AF_XDP and TX via\n+ // AF_PACKET.\n+ AFXDPFD := -1\n+ if args.AFXDP {\n+ oldFD := args.FilePayload.Files[fdOffset].Fd()\n+ newFD, err := unix.Dup(int(oldFD))\n+ if err != nil {\n+ return fmt.Errorf(\"failed to dup AF_XDP fd %v: %v\", oldFD, err)\n+ }\n+ AFXDPFD = newFD\n+ fdOffset++\n+ }\n+\nmac := tcpip.LinkAddress(link.LinkAddress)\nlog.Infof(\"gso max size is: %d\", link.GSOMaxSize)\nlinkEP, err := fdbased.New(&fdbased.Options{\nFDs: FDs,\n+ AFXDPFD: AFXDPFD,\nMTU: uint32(link.MTU),\nEthernetHeader: mac != \"\",\nAddress: mac,\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/config.go", "new_path": "runsc/config/config.go", "diff": "@@ -225,6 +225,10 @@ type Config struct {\n// Use pools to manage buffer memory instead of heap.\nBufferPooling bool `flag:\"buffer-pooling\"`\n+ // AFXDP defines whether to use an AF_XDP socket to receive packets\n+ // (rather than AF_PACKET). Enabling it disables RX checksum offload.\n+ AFXDP bool `flag:\"EXPERIMENTAL-afxdp\"`\n+\n// FDLimit specifies a limit on the number of host file descriptors that can\n// be open simultaneously by the sentry and gofer. It applies separately to\n// each.\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/flags.go", "new_path": "runsc/config/flags.go", "diff": "@@ -96,6 +96,7 @@ func RegisterFlags(flagSet *flag.FlagSet) {\nflagSet.Var(queueingDisciplinePtr(QDiscFIFO), \"qdisc\", \"specifies which queueing discipline to apply by default to the non loopback nics used by the sandbox.\")\nflagSet.Int(\"num-network-channels\", 1, \"number of underlying channels(FDs) to use for network link endpoints.\")\nflagSet.Bool(\"buffer-pooling\", false, \"enable allocation of buffers from a shared pool instead of the heap.\")\n+ flagSet.Bool(\"EXPERIMENTAL-afxdp\", false, \"EXPERIMENTAL. Use an AF_XDP socket to receive packets.\")\n// Test flags, not to be used outside tests, ever.\nflagSet.Bool(\"TESTONLY-unsafe-nonroot\", false, \"TEST ONLY; do not ever use! This skips many security measures that isolate the host from the sandbox.\")\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/network.go", "new_path": "runsc/sandbox/network.go", "diff": "@@ -63,7 +63,7 @@ func setupNetwork(conn *urpc.Client, pid int, conf *config.Config) error {\n// Build the path to the net namespace of the sandbox process.\n// This is what we will copy.\nnsPath := filepath.Join(\"/proc\", strconv.Itoa(pid), \"ns/net\")\n- if err := createInterfacesAndRoutesFromNS(conn, nsPath, conf.HostGSO, conf.GvisorGSO, conf.TXChecksumOffload, conf.RXChecksumOffload, conf.NumNetworkChannels, conf.QDisc); err != nil {\n+ if err := createInterfacesAndRoutesFromNS(conn, nsPath, conf); err != nil {\nreturn fmt.Errorf(\"creating interfaces from net namespace %q: %v\", nsPath, err)\n}\ncase config.NetworkHost:\n@@ -116,7 +116,7 @@ func isRootNS() (bool, error) {\n// createInterfacesAndRoutesFromNS scrapes the interface and routes from the\n// net namespace with the given path, creates them in the sandbox, and removes\n// them from the host.\n-func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hostGSO bool, gvisorGSO bool, txChecksumOffload bool, rxChecksumOffload bool, numNetworkChannels int, qDisc config.QueueingDiscipline) error {\n+func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, conf *config.Config) error {\n// Join the network namespace that we will be copying.\nrestore, err := joinNetNS(nsPath)\nif err != nil {\n@@ -213,14 +213,16 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hostGSO b\nargs.Defaultv6Gateway.Name = iface.Name\n}\n+ args.AFXDP = conf.AFXDP\n+\nlink := boot.FDBasedLink{\nName: iface.Name,\nMTU: iface.MTU,\nRoutes: routes,\n- TXChecksumOffload: txChecksumOffload,\n- RXChecksumOffload: rxChecksumOffload,\n- NumChannels: numNetworkChannels,\n- QDisc: qDisc,\n+ TXChecksumOffload: conf.TXChecksumOffload,\n+ RXChecksumOffload: conf.RXChecksumOffload,\n+ NumChannels: conf.NumNetworkChannels,\n+ QDisc: conf.QDisc,\nNeighbors: neighbors,\n}\n@@ -235,7 +237,7 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hostGSO b\n// Create the socket for the device.\nfor i := 0; i < link.NumChannels; i++ {\nlog.Debugf(\"Creating Channel %d\", i)\n- socketEntry, err := createSocket(iface, ifaceLink, hostGSO)\n+ socketEntry, err := createSocket(iface, ifaceLink, conf.HostGSO, conf.AFXDP)\nif err != nil {\nreturn fmt.Errorf(\"failed to createSocket for %s : %w\", iface.Name, err)\n}\n@@ -250,7 +252,16 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hostGSO b\nargs.FilePayload.Files = append(args.FilePayload.Files, socketEntry.deviceFile)\n}\n- if link.GSOMaxSize == 0 && gvisorGSO {\n+ // If enabled, create an RX socket for AF_XDP.\n+ if conf.AFXDP {\n+ xdpSock, err := createSocketXDP(iface)\n+ if err != nil {\n+ return fmt.Errorf(\"failed to create XDP socket: %v\", err)\n+ }\n+ args.FilePayload.Files = append(args.FilePayload.Files, xdpSock)\n+ }\n+\n+ if link.GSOMaxSize == 0 && conf.GvisorGSO {\n// Host GSO is disabled. Let's enable gVisor GSO.\nlink.GSOMaxSize = stack.GvisorGSOMaxSize\nlink.GvisorGSOEnabled = true\n@@ -313,9 +324,10 @@ type socketEntry struct {\ngsoMaxSize uint32\n}\n-// createSocket creates an underlying AF_PACKET socket and configures it for use by\n-// the sentry and returns an *os.File that wraps the underlying socket fd.\n-func createSocket(iface net.Interface, ifaceLink netlink.Link, enableGSO bool) (*socketEntry, error) {\n+// createSocket creates an underlying AF_PACKET socket and configures it for\n+// use by the sentry and returns an *os.File that wraps the underlying socket\n+// fd.\n+func createSocket(iface net.Interface, ifaceLink netlink.Link, enableGSO bool, AFXDP bool) (*socketEntry, error) {\n// Create the socket.\nconst protocol = 0x0300 // htons(ETH_P_ALL)\nfd, err := unix.Socket(unix.AF_PACKET, unix.SOCK_RAW, protocol)\n@@ -375,6 +387,17 @@ func createSocket(iface net.Interface, ifaceLink netlink.Link, enableGSO bool) (\nreturn &socketEntry{deviceFile, gsoMaxSize}, nil\n}\n+func createSocketXDP(iface net.Interface) (*os.File, error) {\n+ // Create an XDP socket. The sentry will mmap memory for the various\n+ // rings and bind to the device.\n+ fd, err := unix.Socket(unix.AF_XDP, unix.SOCK_RAW, 0)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"unable to create AF_XDP socket: %v\", err)\n+ }\n+ deviceFile := os.NewFile(uintptr(fd), \"xdp-fd\")\n+ return deviceFile, nil\n+}\n+\n// loopbackLink returns the link with addresses and routes for a loopback\n// interface.\nfunc loopbackLink(iface net.Interface, addrs []net.Addr) (boot.LoopbackLink, error) {\n" } ]
Go
Apache License 2.0
google/gvisor
netstack: add --EXPERIMENTAL-afxdp flag Setting the flag creates an AF_XDP socket that will be consumed by the XDP dispatcher. PiperOrigin-RevId: 470109694
259,909
26.08.2022 16:28:59
25,200
23b21af6d631c6574901628ea12ec1e7f7e2324d
Fix JSON marshaling of runsc cgroup configuration.
[ { "change_type": "MODIFY", "old_path": "runsc/cgroup/cgroup.go", "new_path": "runsc/cgroup/cgroup.go", "diff": "@@ -41,9 +41,7 @@ import (\nconst (\ncgroupv1FsName = \"cgroup\"\ncgroupv2FsName = \"cgroup2\"\n-)\n-const (\n// procRoot is the procfs root this module uses.\nprocRoot = \"/proc\"\n@@ -415,67 +413,67 @@ func new(pid, cgroupsPath string, useSystemd bool) (Cgroup, error) {\n// CgroupJSON is a wrapper for Cgroup that can be encoded to JSON.\ntype CgroupJSON struct {\n- Cgroup Cgroup `json:\"cgroup\"`\n- UseSystemd bool `json:\"useSystemd\"`\n+ Cgroup Cgroup\n}\ntype cgroupJSONv1 struct {\n- Cgroup *cgroupV1 `json:\"cgroup\"`\n+ Cgroup *cgroupV1 `json:\"cgroupv1\"`\n}\ntype cgroupJSONv2 struct {\n- Cgroup *cgroupV2 `json:\"cgroup\"`\n+ Cgroup *cgroupV2 `json:\"cgroupv2\"`\n}\ntype cgroupJSONSystemd struct {\n- Cgroup *cgroupSystemd `json:\"cgroup\"`\n+ Cgroup *cgroupSystemd `json:\"cgroupsystemd\"`\n+}\n+\n+type cgroupJSONUnknown struct {\n+ Cgroup interface{} `json:\"cgroupunknown\"`\n}\n// UnmarshalJSON implements json.Unmarshaler.UnmarshalJSON\nfunc (c *CgroupJSON) UnmarshalJSON(data []byte) error {\n- if c.UseSystemd {\n- systemd := cgroupJSONSystemd{}\n- if err := json.Unmarshal(data, &systemd); err != nil {\n+ m := map[string]json.RawMessage{}\n+ if err := json.Unmarshal(data, &m); err != nil {\nreturn err\n}\n- if systemd.Cgroup != nil {\n- c.Cgroup = systemd.Cgroup\n- }\n- return nil\n- }\n- if IsOnlyV2() {\n- v2 := cgroupJSONv2{}\n- err := json.Unmarshal(data, &v2)\n- if v2.Cgroup != nil {\n- c.Cgroup = v2.Cgroup\n- }\n+ var cg Cgroup\n+ if rm, ok := m[\"cgroupv1\"]; ok {\n+ cg = &cgroupV1{}\n+ if err := json.Unmarshal(rm, cg); err != nil {\nreturn err\n}\n- v1 := cgroupJSONv1{}\n- err := json.Unmarshal(data, &v1)\n- if v1.Cgroup != nil {\n- c.Cgroup = v1.Cgroup\n+ } else if rm, ok := m[\"cgroupv2\"]; ok {\n+ cg = &cgroupV2{}\n+ if err := json.Unmarshal(rm, cg); err != nil {\n+ return err\n}\n+ } else if rm, ok := m[\"cgroupsystemd\"]; ok {\n+ cg = &cgroupSystemd{}\n+ if err := json.Unmarshal(rm, cg); err != nil {\nreturn err\n}\n+ }\n+ c.Cgroup = cg\n+ return nil\n+}\n// MarshalJSON implements json.Marshaler.MarshalJSON\nfunc (c *CgroupJSON) MarshalJSON() ([]byte, error) {\nif c.Cgroup == nil {\n- v1 := cgroupJSONv1{}\n- return json.Marshal(&v1)\n- }\n- if IsOnlyV2() {\n- if c.UseSystemd {\n- systemd := cgroupJSONSystemd{Cgroup: c.Cgroup.(*cgroupSystemd)}\n- return json.Marshal(&systemd)\n+ return json.Marshal(cgroupJSONUnknown{})\n}\n- v2 := cgroupJSONv2{Cgroup: c.Cgroup.(*cgroupV2)}\n- return json.Marshal(&v2)\n+ switch c.Cgroup.(type) {\n+ case *cgroupV1:\n+ return json.Marshal(cgroupJSONv1{Cgroup: c.Cgroup.(*cgroupV1)})\n+ case *cgroupV2:\n+ return json.Marshal(cgroupJSONv2{Cgroup: c.Cgroup.(*cgroupV2)})\n+ case *cgroupSystemd:\n+ return json.Marshal(cgroupJSONSystemd{Cgroup: c.Cgroup.(*cgroupSystemd)})\n}\n- v1 := cgroupJSONv1{Cgroup: c.Cgroup.(*cgroupV1)}\n- return json.Marshal(&v1)\n+ return nil, nil\n}\n// Install creates and configures cgroups according to 'res'. If cgroup path\n" }, { "change_type": "MODIFY", "old_path": "runsc/cgroup/cgroup_test.go", "new_path": "runsc/cgroup/cgroup_test.go", "diff": "package cgroup\nimport (\n+ \"encoding/json\"\n\"io/ioutil\"\n\"os\"\n\"path/filepath\"\n@@ -905,3 +906,55 @@ func TestOptional(t *testing.T) {\n})\n}\n}\n+\n+func TestJSON(t *testing.T) {\n+ for _, tc := range []struct {\n+ cg Cgroup\n+ }{\n+ {\n+ cg: &cgroupV1{\n+ Name: \"foobar\",\n+ Parents: map[string]string{\"hello\": \"world\"},\n+ Own: map[string]bool{\"parent\": true},\n+ },\n+ },\n+ {\n+ cg: &cgroupV2{\n+ Mountpoint: \"foobar\",\n+ Path: \"a/path/here\",\n+ Controllers: []string{\"test\", \"controllers\"},\n+ Own: []string{\"I\", \"own\", \"this\"},\n+ },\n+ },\n+ {\n+ cg: CreateMockSystemdCgroup(),\n+ },\n+ {\n+ cg: nil,\n+ },\n+ } {\n+ in := &CgroupJSON{Cgroup: tc.cg}\n+ data, err := json.Marshal(in)\n+ if err != nil {\n+ t.Fatalf(\"could not serialize %v to JSON: %v\", in, err)\n+ }\n+ out := &CgroupJSON{}\n+ if err := json.Unmarshal(data, out); err != nil {\n+ t.Fatalf(\"could not deserialize %v from JSON: %v\", data, err)\n+ }\n+ switch tc.cg.(type) {\n+ case *cgroupSystemd:\n+ if _, ok := out.Cgroup.(*cgroupSystemd); !ok {\n+ t.Errorf(\"cgroup incorrectly deserialized from JSON: got %v, want %v\", out.Cgroup, tc.cg)\n+ }\n+ case *cgroupV1:\n+ if _, ok := out.Cgroup.(*cgroupV1); !ok {\n+ t.Errorf(\"cgroup incorrectly deserialized from JSON: got %v, want %v\", out.Cgroup, tc.cg)\n+ }\n+ case *cgroupV2:\n+ if _, ok := out.Cgroup.(*cgroupV2); !ok {\n+ t.Errorf(\"cgroup incorrectly deserialized from JSON: got %v, want %v\", out.Cgroup, tc.cg)\n+ }\n+ }\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/cgroup/systemd.go", "new_path": "runsc/cgroup/systemd.go", "diff": "@@ -291,3 +291,17 @@ func newProp(name string, units interface{}) systemdDbus.Property {\nValue: dbus.MakeVariant(units),\n}\n}\n+\n+// CreateMockSystemdCgroup returns a mock Cgroup configured for systemd. This\n+// is useful for testing.\n+func CreateMockSystemdCgroup() Cgroup {\n+ return &cgroupSystemd{\n+ Name: \"test\",\n+ ScopePrefix: \"runsc\",\n+ Parent: \"system.slice\",\n+ cgroupV2: cgroupV2{\n+ Mountpoint: \"/sys/fs/cgroup\",\n+ Path: \"/a/random/path\",\n+ },\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/BUILD", "new_path": "runsc/container/BUILD", "diff": "@@ -80,6 +80,7 @@ go_test(\n\"//pkg/unet\",\n\"//pkg/urpc\",\n\"//runsc/boot\",\n+ \"//runsc/cgroup\",\n\"//runsc/config\",\n\"//runsc/flag\",\n\"//runsc/specutils\",\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container_test.go", "new_path": "runsc/container/container_test.go", "diff": "@@ -42,6 +42,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/test/testutil\"\n\"gvisor.dev/gvisor/pkg/urpc\"\n+ \"gvisor.dev/gvisor/runsc/cgroup\"\n\"gvisor.dev/gvisor/runsc/config\"\n\"gvisor.dev/gvisor/runsc/flag\"\n\"gvisor.dev/gvisor/runsc/specutils\"\n@@ -2675,3 +2676,40 @@ func TestProfile(t *testing.T) {\n}\n}\n}\n+\n+// TestSaveSystemdCgroup emulates a sandbox saving while configured with the\n+// systemd cgroup driver.\n+func TestSaveSystemdCgroup(t *testing.T) {\n+ spec, conf := sleepSpecConf(t)\n+ _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\n+ if err != nil {\n+ t.Fatalf(\"error setting up container: %v\", err)\n+ }\n+ defer cleanup()\n+\n+ // Create and start the container.\n+ args := Args{\n+ ID: testutil.RandomContainerID(),\n+ Spec: spec,\n+ BundleDir: bundleDir,\n+ }\n+ cont, err := New(conf, args)\n+ if err != nil {\n+ t.Fatalf(\"error creating container: %v\", err)\n+ }\n+ defer cont.Destroy()\n+\n+ cont.CompatCgroup = cgroup.CgroupJSON{Cgroup: cgroup.CreateMockSystemdCgroup()}\n+ if err := cont.Saver.lock(); err != nil {\n+ t.Fatalf(\"cannot lock container metadata file: %v\", err)\n+ }\n+ if err := cont.saveLocked(); err != nil {\n+ t.Fatalf(\"error saving cgroup: %v\", err)\n+ }\n+ cont.Saver.unlock()\n+ loadCont := Container{}\n+ cont.Saver.load(&loadCont)\n+ if !reflect.DeepEqual(cont.CompatCgroup, loadCont.CompatCgroup) {\n+ t.Errorf(\"CompatCgroup not properly saved: want %v, got %v\", cont.CompatCgroup, loadCont.CompatCgroup)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/sandbox.go", "new_path": "runsc/sandbox/sandbox.go", "diff": "@@ -180,7 +180,6 @@ func New(conf *config.Config, args *Args) (*Sandbox, error) {\nID: args.ID,\nCgroupJSON: cgroup.CgroupJSON{\nCgroup: args.Cgroup,\n- UseSystemd: conf.SystemdCgroup,\n},\nUID: -1, // prevent usage before it's set.\nGID: -1, // prevent usage before it's set.\n" } ]
Go
Apache License 2.0
google/gvisor
Fix JSON marshaling of runsc cgroup configuration. PiperOrigin-RevId: 470357748
259,927
29.08.2022 15:40:05
25,200
4fc63e59f0b70ab84d40d9cde3a877708bb18ca2
Use monotonic time for neighbor entries
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_cache_test.go", "new_path": "pkg/tcpip/stack/neighbor_cache_test.go", "diff": "@@ -61,6 +61,7 @@ func unorderedEventsDiffOpts() []cmp.Option {\ncmpopts.SortSlices(func(a, b testEntryEventInfo) bool {\nreturn strings.Compare(string(a.Entry.Addr), string(b.Entry.Addr)) < 0\n}),\n+ cmp.AllowUnexported(tcpip.MonotonicTime{}),\n}\n}\n@@ -71,6 +72,7 @@ func unorderedEntriesDiffOpts() []cmp.Option {\ncmpopts.SortSlices(func(a, b NeighborEntry) bool {\nreturn strings.Compare(string(a.Addr), string(b.Addr)) < 0\n}),\n+ cmp.AllowUnexported(tcpip.MonotonicTime{}),\n}\n}\n@@ -248,7 +250,7 @@ func TestNeighborCacheGetConfig(t *testing.T) {\n// No events should have been dispatched.\nnudDisp.mu.Lock()\ndefer nudDisp.mu.Unlock()\n- if diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\n}\n@@ -270,7 +272,7 @@ func TestNeighborCacheSetConfig(t *testing.T) {\n// No events should have been dispatched.\nnudDisp.mu.Lock()\ndefer nudDisp.mu.Unlock()\n- if diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\n}\n@@ -296,7 +298,7 @@ func addReachableEntryWithRemoved(nudDisp *testNUDDispatcher, clock *faketime.Ma\nAddr: removedEntry.Addr,\nLinkAddr: removedEntry.LinkAddr,\nState: Reachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n})\n}\n@@ -308,12 +310,12 @@ func addReachableEntryWithRemoved(nudDisp *testNUDDispatcher, clock *faketime.Ma\nAddr: entry.Addr,\nLinkAddr: \"\",\nState: Incomplete,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n})\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -342,12 +344,12 @@ func addReachableEntryWithRemoved(nudDisp *testNUDDispatcher, clock *faketime.Ma\nAddr: entry.Addr,\nLinkAddr: entry.LinkAddr,\nState: Reachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -383,7 +385,7 @@ func TestNeighborCacheEntry(t *testing.T) {\n// No more events should have been dispatched.\nnudDisp.mu.Lock()\ndefer nudDisp.mu.Unlock()\n- if diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\n}\n@@ -414,12 +416,12 @@ func TestNeighborCacheRemoveEntry(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: entry.LinkAddr,\nState: Reachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.Unlock()\nif diff != \"\" {\nt.Fatalf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n@@ -497,7 +499,7 @@ func (c *testContext) overflowCache(opts overflowOptions) error {\nAddr: entry.Addr,\nLinkAddr: entry.LinkAddr,\nState: Reachable,\n- UpdatedAt: c.clock.Now().Add(-durationReachableNanos),\n+ UpdatedAt: c.clock.NowMonotonic().Add(-durationReachableNanos),\n}\nwantUnorderedEntries = append(wantUnorderedEntries, wantEntry)\n}\n@@ -509,7 +511,7 @@ func (c *testContext) overflowCache(opts overflowOptions) error {\n// No more events should have been dispatched.\nc.nudDisp.mu.Lock()\ndefer c.nudDisp.mu.Unlock()\n- if diff := cmp.Diff([]testEntryEventInfo(nil), c.nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff([]testEntryEventInfo(nil), c.nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nreturn fmt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\n@@ -566,12 +568,12 @@ func TestNeighborCacheRemoveEntryThenOverflow(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: entry.LinkAddr,\nState: Reachable,\n- UpdatedAt: c.clock.Now(),\n+ UpdatedAt: c.clock.NowMonotonic(),\n},\n},\n}\nc.nudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, c.nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, c.nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nc.nudDisp.mu.events = nil\nc.nudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -611,12 +613,12 @@ func TestNeighborCacheDuplicateStaticEntryWithSameLinkAddress(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: staticLinkAddr,\nState: Static,\n- UpdatedAt: c.clock.Now(),\n+ UpdatedAt: c.clock.NowMonotonic(),\n},\n},\n}\nc.nudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, c.nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, c.nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nc.nudDisp.mu.events = nil\nc.nudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -629,7 +631,7 @@ func TestNeighborCacheDuplicateStaticEntryWithSameLinkAddress(t *testing.T) {\nc.nudDisp.mu.Lock()\ndefer c.nudDisp.mu.Unlock()\n- if diff := cmp.Diff([]testEntryEventInfo(nil), c.nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff([]testEntryEventInfo(nil), c.nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\n}\n@@ -658,12 +660,12 @@ func TestNeighborCacheDuplicateStaticEntryWithDifferentLinkAddress(t *testing.T)\nAddr: entry.Addr,\nLinkAddr: staticLinkAddr,\nState: Static,\n- UpdatedAt: c.clock.Now(),\n+ UpdatedAt: c.clock.NowMonotonic(),\n},\n},\n}\nc.nudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, c.nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, c.nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nc.nudDisp.mu.events = nil\nc.nudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -684,12 +686,12 @@ func TestNeighborCacheDuplicateStaticEntryWithDifferentLinkAddress(t *testing.T)\nAddr: entry.Addr,\nLinkAddr: staticLinkAddr,\nState: Static,\n- UpdatedAt: c.clock.Now(),\n+ UpdatedAt: c.clock.NowMonotonic(),\n},\n},\n}\nc.nudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, c.nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, c.nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nc.nudDisp.mu.events = nil\nc.nudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -728,12 +730,12 @@ func TestNeighborCacheRemoveStaticEntryThenOverflow(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: staticLinkAddr,\nState: Static,\n- UpdatedAt: c.clock.Now(),\n+ UpdatedAt: c.clock.NowMonotonic(),\n},\n},\n}\nc.nudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, c.nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, c.nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nc.nudDisp.mu.events = nil\nc.nudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -753,12 +755,12 @@ func TestNeighborCacheRemoveStaticEntryThenOverflow(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: staticLinkAddr,\nState: Static,\n- UpdatedAt: c.clock.Now(),\n+ UpdatedAt: c.clock.NowMonotonic(),\n},\n},\n}\nc.nudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, c.nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, c.nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nc.nudDisp.mu.events = nil\nc.nudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -809,7 +811,7 @@ func TestNeighborCacheOverwriteWithStaticEntryThenOverflow(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: entry.LinkAddr,\nState: Reachable,\n- UpdatedAt: c.clock.Now(),\n+ UpdatedAt: c.clock.NowMonotonic(),\n},\n},\n{\n@@ -819,12 +821,12 @@ func TestNeighborCacheOverwriteWithStaticEntryThenOverflow(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: staticLinkAddr,\nState: Static,\n- UpdatedAt: c.clock.Now(),\n+ UpdatedAt: c.clock.NowMonotonic(),\n},\n},\n}\nc.nudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, c.nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, c.nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nc.nudDisp.mu.events = nil\nc.nudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -839,7 +841,7 @@ func TestNeighborCacheOverwriteWithStaticEntryThenOverflow(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: staticLinkAddr,\nState: Static,\n- UpdatedAt: c.clock.Now(),\n+ UpdatedAt: c.clock.NowMonotonic(),\n},\n},\n}\n@@ -870,9 +872,9 @@ func TestNeighborCacheAddStaticEntryThenOverflow(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: entry.LinkAddr,\nState: Static,\n- UpdatedAt: c.clock.Now(),\n+ UpdatedAt: c.clock.NowMonotonic(),\n}\n- if diff := cmp.Diff(want, e); diff != \"\" {\n+ if diff := cmp.Diff(want, e, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"c.linkRes.neigh.entry(%s, \\\"\\\", nil) mismatch (-want, +got):\\n%s\", entry.Addr, diff)\n}\n@@ -885,12 +887,12 @@ func TestNeighborCacheAddStaticEntryThenOverflow(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: entry.LinkAddr,\nState: Static,\n- UpdatedAt: c.clock.Now(),\n+ UpdatedAt: c.clock.NowMonotonic(),\n},\n},\n}\nc.nudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, c.nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, c.nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nc.nudDisp.mu.events = nil\nc.nudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -905,7 +907,7 @@ func TestNeighborCacheAddStaticEntryThenOverflow(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: entry.LinkAddr,\nState: Static,\n- UpdatedAt: c.clock.Now(),\n+ UpdatedAt: c.clock.NowMonotonic(),\n},\n},\n}\n@@ -942,12 +944,12 @@ func TestNeighborCacheClear(t *testing.T) {\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr1,\nState: Static,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -968,7 +970,7 @@ func TestNeighborCacheClear(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: entry.LinkAddr,\nState: Reachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n{\n@@ -978,7 +980,7 @@ func TestNeighborCacheClear(t *testing.T) {\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr1,\nState: Static,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\n@@ -1022,12 +1024,12 @@ func TestNeighborCacheClearThenOverflow(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: entry.LinkAddr,\nState: Reachable,\n- UpdatedAt: c.clock.Now(),\n+ UpdatedAt: c.clock.NowMonotonic(),\n},\n},\n}\nc.nudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, c.nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, c.nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nc.nudDisp.mu.events = nil\nc.nudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -1054,7 +1056,7 @@ func TestNeighborCacheKeepFrequentlyUsed(t *testing.T) {\nclock := faketime.NewManualClock()\nlinkRes := newTestNeighborResolver(&nudDisp, config, clock)\n- startedAt := clock.Now()\n+ startedAt := clock.NowMonotonic()\n// The following logic is very similar to overflowCache, but\n// periodically refreshes the frequently used entry.\n@@ -1124,7 +1126,7 @@ func TestNeighborCacheKeepFrequentlyUsed(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: entry.LinkAddr,\nState: Reachable,\n- UpdatedAt: clock.Now().Add(-durationReachableNanos),\n+ UpdatedAt: clock.NowMonotonic().Add(-durationReachableNanos),\n})\n}\n@@ -1135,7 +1137,7 @@ func TestNeighborCacheKeepFrequentlyUsed(t *testing.T) {\n// No more events should have been dispatched.\nnudDisp.mu.Lock()\ndefer nudDisp.mu.Unlock()\n- if diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\n}\n@@ -1187,7 +1189,7 @@ func TestNeighborCacheConcurrent(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: entry.LinkAddr,\nState: Reachable,\n- UpdatedAt: clock.Now().Add(-durationReachableNanos),\n+ UpdatedAt: clock.NowMonotonic().Add(-durationReachableNanos),\n})\n}\n@@ -1239,9 +1241,9 @@ func TestNeighborCacheReplace(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: updatedLinkAddr,\nState: Delay,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n}\n- if diff := cmp.Diff(want, e); diff != \"\" {\n+ if diff := cmp.Diff(want, e, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"linkRes.neigh.entry(%s, '', nil) mismatch (-want, +got):\\n%s\", entry.Addr, diff)\n}\n}\n@@ -1258,9 +1260,9 @@ func TestNeighborCacheReplace(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: updatedLinkAddr,\nState: Reachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n}\n- if diff := cmp.Diff(want, e); diff != \"\" {\n+ if diff := cmp.Diff(want, e, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"linkRes.neigh.entry(%s, '', nil) mismatch (-want, +got):\\n%s\", entry.Addr, diff)\n}\n}\n@@ -1296,9 +1298,9 @@ func TestNeighborCacheResolutionFailed(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: entry.LinkAddr,\nState: Reachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n}\n- if diff := cmp.Diff(want, got); diff != \"\" {\n+ if diff := cmp.Diff(want, got, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"linkRes.neigh.entry(%s, '', nil) mismatch (-want, +got):\\n%s\", entry.Addr, diff)\n}\n@@ -1400,12 +1402,12 @@ func TestNeighborCacheRetryResolution(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: \"\",\nState: Incomplete,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -1431,12 +1433,12 @@ func TestNeighborCacheRetryResolution(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: \"\",\nState: Unreachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -1450,7 +1452,7 @@ func TestNeighborCacheRetryResolution(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: \"\",\nState: Unreachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n}\nif diff := cmp.Diff(linkRes.neigh.entries(), wantEntries, unorderedEntriesDiffOpts()...); diff != \"\" {\n@@ -1483,12 +1485,12 @@ func TestNeighborCacheRetryResolution(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: \"\",\nState: Incomplete,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -1513,12 +1515,12 @@ func TestNeighborCacheRetryResolution(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: entry.LinkAddr,\nState: Reachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -1536,9 +1538,9 @@ func TestNeighborCacheRetryResolution(t *testing.T) {\nAddr: entry.Addr,\nLinkAddr: entry.LinkAddr,\nState: Reachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n}\n- if diff := cmp.Diff(gotEntry, wantEntry); diff != \"\" {\n+ if diff := cmp.Diff(gotEntry, wantEntry, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Fatalf(\"neighbor entry mismatch (-got, +want):\\n%s\", diff)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_entry.go", "new_path": "pkg/tcpip/stack/neighbor_entry.go", "diff": "@@ -34,7 +34,7 @@ type NeighborEntry struct {\nAddr tcpip.Address\nLinkAddr tcpip.LinkAddress\nState NeighborState\n- UpdatedAt time.Time\n+ UpdatedAt tcpip.MonotonicTime\n}\n// NeighborState defines the state of a NeighborEntry within the Neighbor\n@@ -141,7 +141,7 @@ func newStaticNeighborEntry(cache *neighborCache, addr tcpip.Address, linkAddr t\nAddr: addr,\nLinkAddr: linkAddr,\nState: Static,\n- UpdatedAt: cache.nic.stack.clock.Now(),\n+ UpdatedAt: cache.nic.stack.clock.NowMonotonic(),\n}\nn := &neighborEntry{\ncache: cache,\n@@ -230,7 +230,7 @@ func (e *neighborEntry) cancelTimerLocked() {\n//\n// Precondition: e.mu MUST be locked.\nfunc (e *neighborEntry) removeLocked() {\n- e.mu.neigh.UpdatedAt = e.cache.nic.stack.clock.Now()\n+ e.mu.neigh.UpdatedAt = e.cache.nic.stack.clock.NowMonotonic()\ne.dispatchRemoveEventLocked()\ne.cancelTimerLocked()\n// TODO(https://gvisor.dev/issues/5583): test the case where this function is\n@@ -252,7 +252,7 @@ func (e *neighborEntry) setStateLocked(next NeighborState) {\nprev := e.mu.neigh.State\ne.mu.neigh.State = next\n- e.mu.neigh.UpdatedAt = e.cache.nic.stack.clock.Now()\n+ e.mu.neigh.UpdatedAt = e.cache.nic.stack.clock.NowMonotonic()\nconfig := e.nudState.Config()\nswitch next {\n@@ -360,7 +360,7 @@ func (e *neighborEntry) handlePacketQueuedLocked(localAddr tcpip.Address) {\ncase Unknown, Unreachable:\nprev := e.mu.neigh.State\ne.mu.neigh.State = Incomplete\n- e.mu.neigh.UpdatedAt = e.cache.nic.stack.clock.Now()\n+ e.mu.neigh.UpdatedAt = e.cache.nic.stack.clock.NowMonotonic()\nswitch prev {\ncase Unknown:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_entry_test.go", "new_path": "pkg/tcpip/stack/neighbor_entry_test.go", "diff": "@@ -296,7 +296,7 @@ func TestEntryUnknownToUnknownWhenConfirmationWithUnknownAddress(t *testing.T) {\n// No events should have been dispatched.\nnudDisp.mu.Lock()\n- if diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -352,13 +352,13 @@ func unknownToIncomplete(e *neighborEntry, nudDisp *testNUDDispatcher, linkRes *\nAddr: entryTestAddr1,\nLinkAddr: tcpip.LinkAddress(\"\"),\nState: Incomplete,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\n{\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -413,13 +413,13 @@ func unknownToStale(e *neighborEntry, nudDisp *testNUDDispatcher, linkRes *entry\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr1,\nState: Stale,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\n{\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -483,12 +483,12 @@ func TestEntryIncompleteToIncompleteDoesNotChangeUpdatedAt(t *testing.T) {\nAddr: entryTestAddr1,\nLinkAddr: tcpip.LinkAddress(\"\"),\nState: Unreachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -545,13 +545,13 @@ func incompleteToReachableWithFlags(e *neighborEntry, nudDisp *testNUDDispatcher\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr1,\nState: Reachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\n{\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -642,12 +642,12 @@ func TestEntryIncompleteToStaleWhenUnsolicitedConfirmation(t *testing.T) {\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr1,\nState: Stale,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -676,12 +676,12 @@ func TestEntryIncompleteToStaleWhenProbe(t *testing.T) {\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr1,\nState: Stale,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -755,12 +755,12 @@ func incompleteToUnreachable(c NUDConfigurations, e *neighborEntry, nudDisp *tes\nAddr: entryTestAddr1,\nLinkAddr: tcpip.LinkAddress(\"\"),\nState: Unreachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -819,7 +819,7 @@ func TestEntryReachableToReachableClearsRouterWhenConfirmationWithoutRouter(t *t\n// No events should have been dispatched.\nnudDisp.mu.Lock()\n- diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events)\n+ diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.Unlock()\nif diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n@@ -860,7 +860,7 @@ func TestEntryReachableToReachableWhenProbeWithSameAddress(t *testing.T) {\n// No events should have been dispatched.\nnudDisp.mu.Lock()\n- diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events)\n+ diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.Unlock()\nif diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n@@ -941,14 +941,14 @@ func reachableToStale(c NUDConfigurations, e *neighborEntry, nudDisp *testNUDDis\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr1,\nState: Stale,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\n{\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -996,12 +996,12 @@ func TestEntryReachableToStaleWhenProbeWithDifferentAddress(t *testing.T) {\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr2,\nState: Stale,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -1048,12 +1048,12 @@ func TestEntryReachableToStaleWhenConfirmationWithDifferentAddress(t *testing.T)\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr1,\nState: Stale,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -1100,12 +1100,12 @@ func TestEntryReachableToStaleWhenConfirmationWithDifferentAddressAndOverride(t\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr2,\nState: Stale,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -1189,12 +1189,12 @@ func TestEntryStaleToReachableWhenSolicitedOverrideConfirmation(t *testing.T) {\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr2,\nState: Reachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -1241,12 +1241,12 @@ func TestEntryStaleToReachableWhenSolicitedConfirmationWithoutAddress(t *testing\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr1,\nState: Reachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -1282,12 +1282,12 @@ func TestEntryStaleToStaleWhenOverrideConfirmation(t *testing.T) {\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr2,\nState: Stale,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -1330,12 +1330,12 @@ func TestEntryStaleToStaleWhenProbeUpdateAddress(t *testing.T) {\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr2,\nState: Stale,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -1389,12 +1389,12 @@ func staleToDelay(e *neighborEntry, nudDisp *testNUDDispatcher, linkRes *entryTe\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr1,\nState: Delay,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -1441,12 +1441,12 @@ func TestEntryDelayToReachableWhenUpperLevelConfirmation(t *testing.T) {\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr1,\nState: Reachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -1496,12 +1496,12 @@ func TestEntryDelayToReachableWhenSolicitedOverrideConfirmation(t *testing.T) {\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr2,\nState: Reachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -1551,12 +1551,12 @@ func TestEntryDelayToReachableWhenSolicitedConfirmationWithoutAddress(t *testing\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr1,\nState: Reachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -1643,12 +1643,12 @@ func TestEntryDelayToStaleWhenProbeWithDifferentAddress(t *testing.T) {\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr2,\nState: Stale,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -1695,12 +1695,12 @@ func TestEntryDelayToStaleWhenConfirmationWithDifferentAddress(t *testing.T) {\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr2,\nState: Stale,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -1768,13 +1768,13 @@ func delayToProbe(c NUDConfigurations, e *neighborEntry, nudDisp *testNUDDispatc\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr1,\nState: Probe,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\n{\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -1825,12 +1825,12 @@ func TestEntryProbeToStaleWhenProbeWithDifferentAddress(t *testing.T) {\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr2,\nState: Stale,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -1880,12 +1880,12 @@ func TestEntryProbeToStaleWhenConfirmationWithDifferentAddress(t *testing.T) {\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr2,\nState: Stale,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- if diff := cmp.Diff(wantEvents, nudDisp.mu.events); diff != \"\" {\n+ if diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n}\nnudDisp.mu.Unlock()\n@@ -2001,13 +2001,13 @@ func probeToReachableWithFlags(e *neighborEntry, nudDisp *testNUDDispatcher, lin\nAddr: entryTestAddr1,\nLinkAddr: linkAddr,\nState: Reachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\n{\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -2153,12 +2153,12 @@ func probeToUnreachable(c NUDConfigurations, e *neighborEntry, nudDisp *testNUDD\nAddr: entryTestAddr1,\nLinkAddr: entryTestLinkAddr1,\nState: Unreachable,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n@@ -2225,13 +2225,13 @@ func unreachableToIncomplete(e *neighborEntry, nudDisp *testNUDDispatcher, linkR\nAddr: entryTestAddr1,\nLinkAddr: tcpip.LinkAddress(\"\"),\nState: Incomplete,\n- UpdatedAt: clock.Now(),\n+ UpdatedAt: clock.NowMonotonic(),\n},\n},\n}\n{\nnudDisp.mu.Lock()\n- diff := cmp.Diff(wantEvents, nudDisp.mu.events)\n+ diff := cmp.Diff(wantEvents, nudDisp.mu.events, cmp.AllowUnexported(tcpip.MonotonicTime{}))\nnudDisp.mu.events = nil\nnudDisp.mu.Unlock()\nif diff != \"\" {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nud.go", "new_path": "pkg/tcpip/stack/nud.go", "diff": "@@ -329,7 +329,7 @@ type NUDState struct {\n// the algorithm defined in RFC 4861 section 6.3.2.\nreachableTime time.Duration\n- expiration time.Time\n+ expiration tcpip.MonotonicTime\nprevBaseReachableTime time.Duration\nprevMinRandomFactor float32\nprevMaxRandomFactor float32\n@@ -369,7 +369,7 @@ func (s *NUDState) ReachableTime() time.Duration {\ns.mu.Lock()\ndefer s.mu.Unlock()\n- if s.clock.Now().After(s.mu.expiration) ||\n+ if s.clock.NowMonotonic().After(s.mu.expiration) ||\ns.mu.config.BaseReachableTime != s.mu.prevBaseReachableTime ||\ns.mu.config.MinRandomFactor != s.mu.prevMinRandomFactor ||\ns.mu.config.MaxRandomFactor != s.mu.prevMaxRandomFactor {\n@@ -418,5 +418,5 @@ func (s *NUDState) recomputeReachableTimeLocked() {\ns.mu.reachableTime = time.Duration(reachableTime)\n}\n- s.mu.expiration = s.clock.Now().Add(2 * time.Hour)\n+ s.mu.expiration = s.clock.NowMonotonic().Add(2 * time.Hour)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nud_test.go", "new_path": "pkg/tcpip/stack/nud_test.go", "diff": "@@ -170,8 +170,9 @@ func TestNUDFunctions(t *testing.T) {\nt.Errorf(\"s.Neigbors(%d, %d) error mismatch (-want +got):\\n%s\", test.nicID, ipv6.ProtocolNumber, diff)\n} else if test.expectedErr == nil {\nif diff := cmp.Diff(\n- []stack.NeighborEntry{{Addr: llAddr2, LinkAddr: linkAddr1, State: stack.Static, UpdatedAt: clock.Now()}},\n+ []stack.NeighborEntry{{Addr: llAddr2, LinkAddr: linkAddr1, State: stack.Static, UpdatedAt: clock.NowMonotonic()}},\nneighbors,\n+ cmp.AllowUnexported(tcpip.MonotonicTime{}),\n); diff != \"\" {\nt.Errorf(\"neighbors mismatch (-want +got):\\n%s\", diff)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -5348,8 +5348,9 @@ func TestClearNeighborCacheOnNICDisable(t *testing.T) {\nif neighbors, err := s.Neighbors(nicID, addr.proto); err != nil {\nt.Fatalf(\"s.Neighbors(%d, %d): %s\", nicID, addr.proto, err)\n} else if diff := cmp.Diff(\n- []stack.NeighborEntry{{Addr: addr.addr, LinkAddr: linkAddr, State: stack.Static, UpdatedAt: clock.Now()}},\n+ []stack.NeighborEntry{{Addr: addr.addr, LinkAddr: linkAddr, State: stack.Static, UpdatedAt: clock.NowMonotonic()}},\nneighbors,\n+ cmp.AllowUnexported(tcpip.MonotonicTime{}),\n); diff != \"\" {\nt.Fatalf(\"proto=%d neighbors mismatch (-want +got):\\n%s\", addr.proto, diff)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Use monotonic time for neighbor entries PiperOrigin-RevId: 470832047
259,907
29.08.2022 21:15:18
25,200
0982a5e81db47c16b504f9c0891e77df923ea77c
Change FIXME to NOTE for b/241819530. The comment is not actionable. We might keep seeing old kernels and keep seeing SIGSEGVs.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/32bit.cc", "new_path": "test/syscalls/linux/32bit.cc", "diff": "@@ -165,7 +165,7 @@ TEST(Syscall32Bit, Syscall) {\nbreak;\ncase PlatformSupport::Ignored:\n- // FIXME(b/241819530): SIGSEGV was returned due to a kernel bug that has\n+ // NOTE(b/241819530): SIGSEGV was returned due to a kernel bug that has\n// been fixed recently. Let's continue accept SIGSEGV while bad kernels\n// are running in prod.\nEXPECT_EXIT(ExitGroup32(kSyscall, kExitCode),\n" } ]
Go
Apache License 2.0
google/gvisor
Change FIXME to NOTE for b/241819530. The comment is not actionable. We might keep seeing old kernels and keep seeing SIGSEGVs. PiperOrigin-RevId: 470890652
259,992
30.08.2022 10:46:45
25,200
1aad72663a81205722c4102cfdb62bc789cb1936
Add landing page for Runtime Monitoring
[ { "change_type": "MODIFY", "old_path": "g3doc/user_guide/BUILD", "new_path": "g3doc/user_guide/BUILD", "diff": "@@ -14,27 +14,30 @@ doc(\n)\ndoc(\n- name = \"checkpoint_restore\",\n- src = \"checkpoint_restore.md\",\n+ name = \"install\",\n+ src = \"install.md\",\ncategory = \"User Guide\",\n- permalink = \"/docs/user_guide/checkpoint_restore/\",\n- weight = \"60\",\n+ permalink = \"/docs/user_guide/install/\",\n+ weight = \"10\",\n)\ndoc(\n- name = \"debugging\",\n- src = \"debugging.md\",\n+ name = \"production\",\n+ src = \"production.md\",\ncategory = \"User Guide\",\n- permalink = \"/docs/user_guide/debugging/\",\n- weight = \"70\",\n+ data = [\n+ \"sandboxing-tradeoffs.png\",\n+ ],\n+ permalink = \"/docs/user_guide/production/\",\n+ weight = \"20\",\n)\ndoc(\n- name = \"FAQ\",\n- src = \"FAQ.md\",\n+ name = \"platforms\",\n+ src = \"platforms.md\",\ncategory = \"User Guide\",\n- permalink = \"/docs/user_guide/faq/\",\n- weight = \"90\",\n+ permalink = \"/docs/user_guide/platforms/\",\n+ weight = \"30\",\n)\ndoc(\n@@ -54,28 +57,33 @@ doc(\n)\ndoc(\n- name = \"install\",\n- src = \"install.md\",\n+ name = \"runtime_monitoring\",\n+ src = \"runtime_monitoring.md\",\ncategory = \"User Guide\",\n- permalink = \"/docs/user_guide/install/\",\n- weight = \"10\",\n+ permalink = \"/docs/user_guide/runtimemonitor/\",\n+ weight = \"55\",\n)\ndoc(\n- name = \"platforms\",\n- src = \"platforms.md\",\n+ name = \"checkpoint_restore\",\n+ src = \"checkpoint_restore.md\",\ncategory = \"User Guide\",\n- permalink = \"/docs/user_guide/platforms/\",\n- weight = \"30\",\n+ permalink = \"/docs/user_guide/checkpoint_restore/\",\n+ weight = \"60\",\n)\ndoc(\n- name = \"production\",\n- src = \"production.md\",\n+ name = \"debugging\",\n+ src = \"debugging.md\",\ncategory = \"User Guide\",\n- data = [\n- \"sandboxing-tradeoffs.png\",\n- ],\n- permalink = \"/docs/user_guide/production/\",\n- weight = \"20\",\n+ permalink = \"/docs/user_guide/debugging/\",\n+ weight = \"70\",\n+)\n+\n+doc(\n+ name = \"FAQ\",\n+ src = \"FAQ.md\",\n+ category = \"User Guide\",\n+ permalink = \"/docs/user_guide/faq/\",\n+ weight = \"90\",\n)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "g3doc/user_guide/runtime_monitoring.md", "diff": "+# Runtime Monitoring\n+\n+The runtime monitoring feature provides an interface to observe runtime behavior\n+of applications running inside gVisor. Although it can be used for many\n+purposes, it was built with the primary focus on threat detection. Out of the\n+box, gVisor comes with support to stream application actions (called trace\n+points) to an external process, that is used to validate the actions and alert\n+when abnormal behavior is detected. Trace points are available for all syscalls\n+and other important events in the system, e.g. container start. More trace\n+points can be easily added as needed. The trace points are sent to a process\n+running alongside the sandbox, which is isolated from the sandbox for security\n+reasons. Additionally, the monitoring process can be shared by many sandboxes.\n+\n+You can use the following links to learn more:\n+\n+* [Overview](https://github.com/google/gvisor/blob/master/pkg/sentry/seccheck/README.md)\n+* [How to implement a monitoring process](https://github.com/google/gvisor/blob/master/pkg/sentry/seccheck/sinks/remote/README.md)\n+* [Design document](https://docs.google.com/document/d/1RQQKzeFpO-zOoBHZLA-tr5Ed_bvAOLDqgGgKhqUff2A)\n+* [Configuring Falco with gVisor](https://gvisor.dev/docs/tutorials/falco/)\n+* [Tracereplay tool for testing](https://github.com/google/gvisor/blob/master/tools/tracereplay/README.md)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/seccheck/sinks/remote/README.md", "new_path": "pkg/sentry/seccheck/sinks/remote/README.md", "diff": "# Introduction\n-The remote sink implements a protocol that allows a remote process to receive a\n-stream of trace points being triggered inside the sandbox. The remote sink uses\n-Unix-domain socket (UDS) to connect to the remote process. The remote process is\n-expected to have already created the UDS and be listening to new connections.\n-This allows for a single process to monitor all sandboxes in the machine and\n+The remote sink implements a protocol that allows remote processes to monitor\n+actions being taken inside the sandbox. This document provides information\n+required to implement a monitoring process that consumes trace points. The\n+remote sink uses a Unix-domain socket (UDS) for communication. It opens a new\n+connection and sends a stream of trace points being triggered inside the sandbox\n+to the monitoring process. The monitoring process is expected to have already\n+created the UDS and be listening for new connections. This allows for a single\n+process to monitor all sandboxes in the machine, for better resource usage, and\nsimplifies lifecycle management. When a new sandbox starts, it creates a new\nconnection. And when a sandbox exits, the connection is terminated.\n" }, { "change_type": "MODIFY", "old_path": "website/BUILD", "new_path": "website/BUILD", "diff": "@@ -157,6 +157,7 @@ docs(\n\"//g3doc/user_guide:networking\",\n\"//g3doc/user_guide:platforms\",\n\"//g3doc/user_guide:production\",\n+ \"//g3doc/user_guide:runtime_monitoring\",\n\"//g3doc/user_guide/containerd:configuration\",\n\"//g3doc/user_guide/containerd:containerd_11\",\n\"//g3doc/user_guide/containerd:quick_start\",\n" } ]
Go
Apache License 2.0
google/gvisor
Add landing page for Runtime Monitoring PiperOrigin-RevId: 471033778
259,909
30.08.2022 15:51:26
25,200
e0aa478022f4c3fde1b9619a11421c803e0c0791
Ignore systemd "scope already exists" errors. This copies the behavior of runc. See
[ { "change_type": "MODIFY", "old_path": "runsc/cgroup/systemd.go", "new_path": "runsc/cgroup/systemd.go", "diff": "@@ -181,6 +181,8 @@ func (c *cgroupSystemd) Join() (func(), error) {\nc.dbusConn.ResetFailedUnitContext(ctx, unitName)\nreturn nil, fmt.Errorf(\"unknown job completion status %q\", s)\n}\n+ } else if unitAlreadyExists(err) {\n+ return clean.Release(), nil\n} else {\nreturn nil, fmt.Errorf(\"systemd error: %v\", err)\n}\n@@ -190,6 +192,18 @@ func (c *cgroupSystemd) Join() (func(), error) {\nreturn clean.Release(), nil\n}\n+// unitAlreadyExists returns true if the error is that a systemd unit already\n+// exists.\n+func unitAlreadyExists(err error) bool {\n+ if err != nil {\n+ var derr dbus.Error\n+ if errors.As(err, &derr) {\n+ return strings.Contains(derr.Name, \"org.freedesktop.systemd1.UnitExists\")\n+ }\n+ }\n+ return false\n+}\n+\n// systemd represents slice hierarchy using `-`, so we need to follow suit when\n// generating the path of slice. Essentially, test-a-b.slice becomes\n// /test.slice/test-a.slice/test-a-b.slice.\n" }, { "change_type": "MODIFY", "old_path": "test/root/cgroup_test.go", "new_path": "test/root/cgroup_test.go", "diff": "@@ -567,3 +567,44 @@ func TestCgroupParent(t *testing.T) {\nt.Errorf(\"cgroup control %q processes (%s): %v\", \"cpuacct\", path, err)\n}\n}\n+\n+func TestSystemdCgroupJoinTwice(t *testing.T) {\n+ ctx := context.Background()\n+ d := dockerutil.MakeContainer(ctx, t)\n+ defer d.CleanUp(ctx)\n+ useSystemd, err := dockerutil.UsingSystemdCgroup()\n+ if err != nil {\n+ t.Fatalf(\"docker run failed: %v\", err)\n+ }\n+ if !useSystemd {\n+ t.Skip()\n+ }\n+\n+ // Construct a known cgroup name.\n+ parent := \"system-runsc.slice\"\n+ conf, hostconf, _ := d.ConfigsFrom(dockerutil.RunOpts{\n+ Image: \"basic/alpine\",\n+ }, \"sleep\", \"10000\")\n+ hostconf.Resources.CgroupParent = parent\n+\n+ if err := d.CreateFrom(ctx, \"basic/alpine\", conf, hostconf, nil); err != nil {\n+ t.Fatalf(\"create failed with: %v\", err)\n+ }\n+\n+ if err := d.Start(ctx); err != nil {\n+ t.Fatalf(\"start failed with: %v\", err)\n+ }\n+\n+ // Extract the ID to look up the cgroup.\n+ gid := d.ID()\n+ t.Logf(\"cgroup ID: %s\", gid)\n+\n+ cgroups, err := cgroup.NewFromPath(parent+\":docker:\"+gid, true /* useSystemd */)\n+ if err != nil {\n+ t.Fatalf(\"cgroup.NewFromPath: %v\", err)\n+ }\n+ // Joining a cgroup twice should not produce an error.\n+ if _, err := cgroups.Join(); err != nil {\n+ t.Fatalf(\"Join(): got error rejoining cgroup: %v\", err)\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Ignore systemd "scope already exists" errors. This copies the behavior of runc. See https://github.com/opencontainers/runc/blob/4a51b047036cf16d4f124548c2a7ff24b5640bad/libcontainer/cgroups/systemd/common.go#L150 PiperOrigin-RevId: 471110557
259,909
30.08.2022 18:38:31
25,200
3404bfa49a386009469d36209884fca93d37a8e3
Refactor sharedmem tx.transmit to use bufferv2. This reduces the amount of garbage produced by the methods.
[ { "change_type": "MODIFY", "old_path": "pkg/bufferv2/buffer.go", "new_path": "pkg/bufferv2/buffer.go", "diff": "@@ -571,6 +571,11 @@ func (br *BufferReader) Close() {\nbr.b.Release()\n}\n+// Len returns the number of bytes in the unread portion of the buffer.\n+func (br *BufferReader) Len() int {\n+ return int(br.b.Size())\n+}\n+\n// Range specifies a range of buffer.\ntype Range struct {\nbegin int\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/sharedmem/server_tx.go", "new_path": "pkg/tcpip/link/sharedmem/server_tx.go", "diff": "@@ -20,10 +20,12 @@ package sharedmem\nimport (\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/atomicbitops\"\n+ \"gvisor.dev/gvisor/pkg/bufferv2\"\n\"gvisor.dev/gvisor/pkg/cleanup\"\n\"gvisor.dev/gvisor/pkg/eventfd\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/sharedmem/pipe\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/sharedmem/queue\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n// serverTx represents the server end of the sharedmem queue and is used to send\n@@ -113,12 +115,9 @@ func (s *serverTx) cleanup() {\n// acquireBuffers acquires enough buffers to hold all the data in views or\n// returns nil if not enough buffers are currently available.\n-func (s *serverTx) acquireBuffers(views [][]byte, buffers []queue.RxBuffer) (acquiredBuffers []queue.RxBuffer) {\n+func (s *serverTx) acquireBuffers(pktBuffer bufferv2.Buffer, buffers []queue.RxBuffer) (acquiredBuffers []queue.RxBuffer) {\nacquiredBuffers = buffers[:0]\n- wantBytes := 0\n- for i := range views {\n- wantBytes += len(views[i])\n- }\n+ wantBytes := int(pktBuffer.Size())\nfor wantBytes > 0 {\nvar b []byte\nif b = s.fillPipe.Pull(); b == nil {\n@@ -137,45 +136,32 @@ func (s *serverTx) acquireBuffers(views [][]byte, buffers []queue.RxBuffer) (acq\n// well as the total number of bytes copied.\n//\n// To avoid allocations the filledBuffers are appended to the buffers slice\n-// which will be grown as required.\n-func (s *serverTx) fillPacket(views [][]byte, buffers []queue.RxBuffer) (filledBuffers []queue.RxBuffer, totalCopied uint32) {\n- // fillBuffer copies as much of the views as possible into the provided buffer\n- // and returns any left over views (if any).\n- fillBuffer := func(buffer *queue.RxBuffer, views [][]byte) (left [][]byte) {\n- if len(views) == 0 {\n- return nil\n- }\n- copied := uint64(0)\n- availBytes := buffer.Size\n- for availBytes > 0 && len(views) > 0 {\n- n := copy(s.data[buffer.Offset+copied:][:uint64(buffer.Size)-copied], views[0])\n- copied += uint64(n)\n- availBytes -= uint32(n)\n- views[0] = views[0][n:]\n- if len(views[0]) != 0 {\n- break\n- }\n- views = views[1:]\n- }\n- buffer.Size = uint32(copied)\n- return views\n- }\n- bufs := s.acquireBuffers(views, buffers)\n+// which will be grown as required. This method takes ownership of pktBuffer.\n+func (s *serverTx) fillPacket(pktBuffer bufferv2.Buffer, buffers []queue.RxBuffer) (filledBuffers []queue.RxBuffer, totalCopied uint32) {\n+ bufs := s.acquireBuffers(pktBuffer, buffers)\nif bufs == nil {\n+ pktBuffer.Release()\nreturn nil, 0\n}\n- for i := 0; len(views) > 0 && i < len(bufs); i++ {\n+ br := pktBuffer.AsBufferReader()\n+ defer br.Close()\n+\n+ for i := 0; br.Len() > 0 && i < len(bufs); i++ {\n+ buf := bufs[i]\n+ copied, err := br.Read(s.data[buf.Offset:][:buf.Size])\n+ buf.Size = uint32(copied)\n// Copy the packet into the posted buffer.\n- views = fillBuffer(&bufs[i], views)\ntotalCopied += bufs[i].Size\n+ if err != nil {\n+ return bufs, totalCopied\n+ }\n}\n-\nreturn bufs, totalCopied\n}\n-func (s *serverTx) transmit(views [][]byte) bool {\n+func (s *serverTx) transmit(pkt *stack.PacketBuffer) bool {\nbuffers := make([]queue.RxBuffer, 8)\n- buffers, totalCopied := s.fillPacket(views, buffers)\n+ buffers, totalCopied := s.fillPacket(pkt.ToBuffer(), buffers)\nif totalCopied == 0 {\n// drop the packet as not enough buffers were probably available\n// to send.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/sharedmem/sharedmem.go", "new_path": "pkg/tcpip/link/sharedmem/sharedmem.go", "diff": "@@ -343,11 +343,10 @@ func (e *endpoint) writePacketLocked(r stack.RouteInfo, protocol tcpip.NetworkPr\ne.AddVirtioNetHeader(pkt)\n}\n- views := pkt.AsSlices()\n// Transmit the packet.\n- // TODO(b/231582970): Change transmit() to take a bufferv2.Buffer instead of a\n- // collection of slices.\n- ok := e.tx.transmit(views...)\n+ b := pkt.ToBuffer()\n+ defer b.Release()\n+ ok := e.tx.transmit(b)\nif !ok {\nreturn &tcpip.ErrWouldBlock{}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/sharedmem/sharedmem_server.go", "new_path": "pkg/tcpip/link/sharedmem/sharedmem_server.go", "diff": "@@ -228,8 +228,7 @@ func (e *serverEndpoint) writePacketLocked(r stack.RouteInfo, protocol tcpip.Net\ne.AddVirtioNetHeader(pkt)\n}\n- views := pkt.AsSlices()\n- ok := e.tx.transmit(views)\n+ ok := e.tx.transmit(pkt)\nif !ok {\nreturn &tcpip.ErrWouldBlock{}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/sharedmem/tx.go", "new_path": "pkg/tcpip/link/sharedmem/tx.go", "diff": "@@ -18,6 +18,7 @@ import (\n\"math\"\n\"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/bufferv2\"\n\"gvisor.dev/gvisor/pkg/eventfd\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/sharedmem/queue\"\n)\n@@ -92,7 +93,7 @@ func (t *tx) cleanup() {\n// transmit sends a packet made of bufs. Returns a boolean that specifies\n// whether the packet was successfully transmitted.\n-func (t *tx) transmit(bufs ...[]byte) bool {\n+func (t *tx) transmit(buffer bufferv2.Buffer) bool {\n// Pull completions from the tx queue and add their buffers back to the\n// pool so that we can reuse them.\nfor {\n@@ -107,10 +108,7 @@ func (t *tx) transmit(bufs ...[]byte) bool {\n}\nbSize := t.bufs.entrySize\n- total := uint32(0)\n- for _, data := range bufs {\n- total += uint32(len(data))\n- }\n+ total := uint32(buffer.Size())\nbufCount := (total + bSize - 1) / bSize\n// Allocate enough buffers to hold all the data.\n@@ -132,17 +130,17 @@ func (t *tx) transmit(bufs ...[]byte) bool {\n// Copy data into allocated buffers.\nnBuf := buf\nvar dBuf []byte\n- for _, data := range bufs {\n- for len(data) > 0 {\n+ buffer.Apply(func(v *bufferv2.View) {\n+ for v.Size() > 0 {\nif len(dBuf) == 0 {\ndBuf = t.data[nBuf.Offset:][:nBuf.Size]\nnBuf = nBuf.Next\n}\n- n := copy(dBuf, data)\n- data = data[n:]\n+ n := copy(dBuf, v.AsSlice())\n+ v.TrimFront(n)\ndBuf = dBuf[n:]\n}\n- }\n+ })\n// Get an id for this packet and send it out.\nid := t.ids.add(buf)\n" } ]
Go
Apache License 2.0
google/gvisor
Refactor sharedmem tx.transmit to use bufferv2. This reduces the amount of garbage produced by the methods. PiperOrigin-RevId: 471141815
259,975
31.08.2022 10:54:02
25,200
7c6d90e28f39a57e93fc89bb2d59957ee6bd5ff4
Fix make-push% rule for presubmit images.
[ { "change_type": "MODIFY", "old_path": "tools/images.mk", "new_path": "tools/images.mk", "diff": "@@ -154,6 +154,7 @@ load-%: register-cross ## Pull or build an image locally.\n# the fully-expanded remote image tag.\npush-%: load-% ## Push a given image.\n@docker image push $(call remote_image,$*):$(call tag,$*) >&2\n+ @docker image tag $(call remote_image,$*) $(call remote_image,$*):latest >&2\n@docker image push $(call remote_image,$*):latest >&2\n# register-cross registers the necessary qemu binaries for cross-compilation.\n" } ]
Go
Apache License 2.0
google/gvisor
Fix make-push% rule for presubmit images. PiperOrigin-RevId: 471296093
259,977
31.08.2022 13:02:23
25,200
7203e8aceed1d4d619c4855a25513644a0c49f18
Fix logs in loopback test udp.ProtocolNumber ==> tcp.ProtocolNumber
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/integration/loopback_test.go", "new_path": "pkg/tcpip/tests/integration/loopback_test.go", "diff": "@@ -452,7 +452,7 @@ func TestLoopbackAcceptAllInSubnetTCP(t *testing.T) {\ndefer wq.EventUnregister(&we)\nlisteningEndpoint, err := s.NewEndpoint(tcp.ProtocolNumber, test.addAddress.Protocol, &wq)\nif err != nil {\n- t.Fatalf(\"NewEndpoint(%d, %d, _): %s\", udp.ProtocolNumber, test.addAddress.Protocol, err)\n+ t.Fatalf(\"NewEndpoint(%d, %d, _): %s\", tcp.ProtocolNumber, test.addAddress.Protocol, err)\n}\ndefer listeningEndpoint.Close()\n@@ -467,7 +467,7 @@ func TestLoopbackAcceptAllInSubnetTCP(t *testing.T) {\nconnectingEndpoint, err := s.NewEndpoint(tcp.ProtocolNumber, test.addAddress.Protocol, &wq)\nif err != nil {\n- t.Fatalf(\"s.NewEndpoint(%d, %d, _): %s\", udp.ProtocolNumber, test.addAddress.Protocol, err)\n+ t.Fatalf(\"s.NewEndpoint(%d, %d, _): %s\", tcp.ProtocolNumber, test.addAddress.Protocol, err)\n}\ndefer connectingEndpoint.Close()\n" } ]
Go
Apache License 2.0
google/gvisor
Fix logs in loopback test udp.ProtocolNumber ==> tcp.ProtocolNumber PiperOrigin-RevId: 471329935
259,909
31.08.2022 13:37:01
25,200
b9f04e4000a9668f3528af2e590c5b23254a7125
Refactor TestHandshakeTimeoutConnectCount to use a fake clock. This makes the test take 2 seconds instead of 2+ minutes.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/test/e2e/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/test/e2e/tcp_test.go", "diff": "@@ -293,7 +293,13 @@ func TestCloseWithoutConnect(t *testing.T) {\n}\nfunc TestHandshakeTimeoutConnectedCount(t *testing.T) {\n- c := context.New(t, e2e.DefaultMTU)\n+ clock := faketime.NewManualClock()\n+ c := context.NewWithOpts(t, context.Options{\n+ EnableV4: true,\n+ EnableV6: true,\n+ MTU: e2e.DefaultMTU,\n+ Clock: clock,\n+ })\ndefer c.Cleanup()\nep, err := c.Stack().NewEndpoint(tcp.ProtocolNumber, ipv4.ProtocolNumber, &c.WQ)\n@@ -312,6 +318,8 @@ func TestHandshakeTimeoutConnectedCount(t *testing.T) {\nt.Fatalf(\"Connect did not start: %v\", err)\n}\n+ clock.Advance(tcp.DefaultKeepaliveInterval)\n+ clock.Advance(tcp.DefaultKeepaliveInterval)\n<-ch\nswitch err := c.EP.LastError().(type) {\ncase *tcpip.ErrTimeout:\n" } ]
Go
Apache License 2.0
google/gvisor
Refactor TestHandshakeTimeoutConnectCount to use a fake clock. This makes the test take 2 seconds instead of 2+ minutes. PiperOrigin-RevId: 471341662
259,853
31.08.2022 15:39:21
25,200
479fd558e12f2985878d9634c6ec93304cdc2e4b
ring0: fix off-by-one bug in IsCanonical
[ { "change_type": "MODIFY", "old_path": "pkg/ring0/kernel_amd64.go", "new_path": "pkg/ring0/kernel_amd64.go", "diff": "@@ -215,7 +215,7 @@ func (c *CPU) EFER() uint64 {\n//\n//go:nosplit\nfunc IsCanonical(addr uint64) bool {\n- return addr <= 0x00007fffffffffff || addr > 0xffff800000000000\n+ return addr <= 0x00007fffffffffff || addr >= 0xffff800000000000\n}\n// SwitchToUser performs either a sysret or an iret.\n" }, { "change_type": "MODIFY", "old_path": "pkg/ring0/kernel_arm64.go", "new_path": "pkg/ring0/kernel_arm64.go", "diff": "@@ -54,7 +54,7 @@ func (c *CPU) StackTop() uint64 {\n//\n//go:nosplit\nfunc IsCanonical(addr uint64) bool {\n- return addr <= 0x0000ffffffffffff || addr > 0xffff000000000000\n+ return addr <= 0x0000ffffffffffff || addr >= 0xffff000000000000\n}\n// SwitchToUser performs an eret.\n" } ]
Go
Apache License 2.0
google/gvisor
ring0: fix off-by-one bug in IsCanonical PiperOrigin-RevId: 471373714
259,975
01.09.2022 12:18:26
25,200
be5faaf19ba692569256ba9d906edada3377480a
Remove latest tag from Makefile Remove the call to tag images with the "latest" tag. This is unnecessary for CI builds and it is currently breaking the release pipeline.
[ { "change_type": "MODIFY", "old_path": "tools/images.mk", "new_path": "tools/images.mk", "diff": "@@ -154,8 +154,6 @@ load-%: register-cross ## Pull or build an image locally.\n# the fully-expanded remote image tag.\npush-%: load-% ## Push a given image.\n@docker image push $(call remote_image,$*):$(call tag,$*) >&2\n- @docker image tag $(call remote_image,$*) $(call remote_image,$*):latest >&2\n- @docker image push $(call remote_image,$*):latest >&2\n# register-cross registers the necessary qemu binaries for cross-compilation.\n# This may be used by any target that may execute containers that are not the\n" } ]
Go
Apache License 2.0
google/gvisor
Remove latest tag from Makefile Remove the call to tag images with the "latest" tag. This is unnecessary for CI builds and it is currently breaking the release pipeline. PiperOrigin-RevId: 471600547
259,909
01.09.2022 16:42:13
25,200
dade50095a41bdf3ea2bec8085dc1e87709bbe89
Use a pool for segments. This will improve the performance of newIncomingSegment, newOutgoingSegment, and clone.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/segment.go", "new_path": "pkg/tcpip/transport/tcp/segment.go", "diff": "@@ -19,6 +19,7 @@ import (\n\"io\"\n\"gvisor.dev/gvisor/pkg/bufferv2\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n@@ -39,6 +40,12 @@ const (\nsendQ\n)\n+var segmentPool = sync.Pool{\n+ New: func() interface{} {\n+ return &segment{}\n+ },\n+}\n+\n// segment represents a TCP segment. It holds the payload and parsed TCP segment\n// information, and can be added to intrusive lists.\n// segment is mostly immutable, the only field allowed to change is data.\n@@ -99,21 +106,19 @@ func newIncomingSegment(id stack.TransportEndpointID, clock tcpip.Clock, pkt *st\nreturn nil, fmt.Errorf(\"header data offset does not respect size constraints: %d < offset < %d, got offset=%d\", header.TCPMinimumSize, len(hdr), hdr.DataOffset())\n}\n- s := &segment{\n- id: id,\n- options: hdr[header.TCPMinimumSize:],\n- parsedOptions: header.ParseTCPOptions(hdr[header.TCPMinimumSize:]),\n- sequenceNumber: seqnum.Value(hdr.SequenceNumber()),\n- ackNumber: seqnum.Value(hdr.AckNumber()),\n- flags: hdr.Flags(),\n- window: seqnum.Size(hdr.WindowSize()),\n- rcvdTime: clock.NowMonotonic(),\n- dataMemSize: pkt.MemSize(),\n- pkt: pkt,\n- csumValid: csumValid,\n- }\n+ s := newSegment()\n+ s.id = id\n+ s.options = hdr[header.TCPMinimumSize:]\n+ s.parsedOptions = header.ParseTCPOptions(hdr[header.TCPMinimumSize:])\n+ s.sequenceNumber = seqnum.Value(hdr.SequenceNumber())\n+ s.ackNumber = seqnum.Value(hdr.AckNumber())\n+ s.flags = hdr.Flags()\n+ s.window = seqnum.Size(hdr.WindowSize())\n+ s.rcvdTime = clock.NowMonotonic()\n+ s.dataMemSize = pkt.MemSize()\n+ s.pkt = pkt\npkt.IncRef()\n- s.InitRefs()\n+ s.csumValid = csumValid\nif !s.pkt.RXTransportChecksumValidated {\ns.csum = csum\n@@ -122,10 +127,8 @@ func newIncomingSegment(id stack.TransportEndpointID, clock tcpip.Clock, pkt *st\n}\nfunc newOutgoingSegment(id stack.TransportEndpointID, clock tcpip.Clock, buf bufferv2.Buffer) *segment {\n- s := &segment{\n- id: id,\n- }\n- s.InitRefs()\n+ s := newSegment()\n+ s.id = id\ns.rcvdTime = clock.NowMonotonic()\ns.pkt = stack.NewPacketBuffer(stack.PacketBufferOptions{Payload: buf})\ns.dataMemSize = s.pkt.MemSize()\n@@ -133,24 +136,29 @@ func newOutgoingSegment(id stack.TransportEndpointID, clock tcpip.Clock, buf buf\n}\nfunc (s *segment) clone() *segment {\n- t := &segment{\n- id: s.id,\n- sequenceNumber: s.sequenceNumber,\n- ackNumber: s.ackNumber,\n- flags: s.flags,\n- window: s.window,\n- rcvdTime: s.rcvdTime,\n- xmitTime: s.xmitTime,\n- xmitCount: s.xmitCount,\n- ep: s.ep,\n- qFlags: s.qFlags,\n- dataMemSize: s.dataMemSize,\n- }\n- t.InitRefs()\n+ t := newSegment()\n+ t.id = s.id\n+ t.sequenceNumber = s.sequenceNumber\n+ t.ackNumber = s.ackNumber\n+ t.flags = s.flags\n+ t.window = s.window\n+ t.rcvdTime = s.rcvdTime\n+ t.xmitTime = s.xmitTime\n+ t.xmitCount = s.xmitCount\n+ t.ep = s.ep\n+ t.qFlags = s.qFlags\n+ t.dataMemSize = s.dataMemSize\nt.pkt = s.pkt.Clone()\nreturn t\n}\n+func newSegment() *segment {\n+ s := segmentPool.Get().(*segment)\n+ *s = segment{}\n+ s.InitRefs()\n+ return s\n+}\n+\n// merge merges data in oth and clears oth.\nfunc (s *segment) merge(oth *segment) {\ns.pkt.Data().Merge(oth.pkt.Data())\n@@ -176,8 +184,6 @@ func (s *segment) setOwner(ep *endpoint, qFlags queueFlags) {\nfunc (s *segment) DecRef() {\ns.segmentRefs.DecRef(func() {\n- defer s.pkt.DecRef()\n- s.pkt = nil\nif s.ep != nil {\nswitch s.qFlags {\ncase recvQ:\n@@ -188,6 +194,9 @@ func (s *segment) DecRef() {\npanic(fmt.Sprintf(\"unexpected queue flag %b set for segment\", s.qFlags))\n}\n}\n+ s.pkt.DecRef()\n+ s.pkt = nil\n+ segmentPool.Put(s)\n})\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Use a pool for segments. This will improve the performance of newIncomingSegment, newOutgoingSegment, and clone. PiperOrigin-RevId: 471666528
259,950
02.09.2022 11:13:41
-28,800
29793cb7f8f7e6234c09c4156c720b30aaebae1c
images.mk: make sort result stable to generate the same image tag at diffrent machines
[ { "change_type": "MODIFY", "old_path": "tools/images.mk", "new_path": "tools/images.mk", "diff": "@@ -76,7 +76,7 @@ dockerfile = $$(if [ -f \"$(call path,$(1))/Dockerfile.$(ARCH)\" ]; then echo Dock\n# The tag construct is used to memoize the image generated (see README.md).\n# This scheme is used to enable aggressive caching in a central repository, but\n# ensuring that images will always be sourced using the local files.\n-tag = $(shell cd images && find $(subst _,/,$(1)) -type f | sort | xargs -n 1 sha256sum | sha256sum - | cut -c 1-16)\n+tag = $(shell cd images && find $(subst _,/,$(1)) -type f | sort -f -d | xargs -n 1 sha256sum | sha256sum - | cut -c 1-16)\nremote_image = $(REMOTE_IMAGE_PREFIX)/$(subst _,/,$(1))_$(ARCH)\nlocal_image = $(LOCAL_IMAGE_PREFIX)/$(subst _,/,$(1))\n" } ]
Go
Apache License 2.0
google/gvisor
images.mk: make sort result stable to generate the same image tag at diffrent machines Signed-off-by: Tan Yifeng <yiftan@163.com>
259,932
02.09.2022 13:34:07
25,200
a3a57724912c54d4c464c329452ff789471b408f
Fixes to TTOU handling in TIOCSPGRP Fixes two issues in TTOU handling while handling TIOCSPGRP on a tty device. fixes see that issue for details of the bugs. Updates the tests to test the fixed behavior; both tests are verified to fail without the `thread_group.go` fixes.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/thread_group.go", "new_path": "pkg/sentry/kernel/thread_group.go", "diff": "@@ -514,9 +514,10 @@ func (tg *ThreadGroup) SetForegroundProcessGroup(tty *TTY, pgid ProcessGroupID)\n// signal is sent to all members of this background process group.\n// We need also need to check whether it is ignoring or blocking SIGTTOU.\nignored := signalAction.Handler == linux.SIG_IGN\n- blocked := linux.SignalSet(tg.leader.signalMask.RacyLoad()) == linux.SignalSetOf(linux.SIGTTOU)\n+ blocked := (linux.SignalSet(tg.leader.signalMask.RacyLoad()) & linux.SignalSetOf(linux.SIGTTOU)) != 0\nif tg.processGroup.id != tg.processGroup.session.foreground.id && !ignored && !blocked {\ntg.leader.sendSignalLocked(SignalInfoPriv(linux.SIGTTOU), true)\n+ return -1, linuxerr.ERESTARTSYS\n}\ntg.processGroup.session.foreground.id = pgid\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/pty.cc", "new_path": "test/syscalls/linux/pty.cc", "diff": "@@ -1656,6 +1656,10 @@ TEST_F(JobControlTest, SetForegroundProcessGroupSIGTTOUBackground) {\nint wstatus;\nTEST_PCHECK(waitpid(grandchild, &wstatus, WSTOPPED) == grandchild);\nTEST_PCHECK(WSTOPSIG(wstatus) == SIGTTOU);\n+\n+ // The child's `tcsetpgrp` got signalled and so should not have\n+ // taken effect. Verify that.\n+ TEST_PCHECK(tcgetpgrp(replica_.get()) == getpid());\nEXPECT_THAT(kill(grandchild, SIGKILL), SyscallSucceeds());\n});\nASSERT_NO_ERRNO(res);\n@@ -1703,11 +1707,20 @@ TEST_F(JobControlTest, SetForegroundProcessGroupSIGTTOUBlocked) {\nsigset_t signal_set;\nsigemptyset(&signal_set);\nsigaddset(&signal_set, SIGTTOU);\n+ // Block SIGTTIN as well, to make sure that the kernel isn't\n+ // checking for \"blocked == [SIGTTOU]\" (see issue 7941 for\n+ // context).\n+ sigaddset(&signal_set, SIGTTIN);\nsigprocmask(SIG_BLOCK, &signal_set, NULL);\n// Assign a different pgid to the child so it will result as\n// a background process.\nTEST_PCHECK(!setpgid(grandchild, getpid()));\nTEST_PCHECK(!tcsetpgrp(replica_.get(), getpgid(0)));\n+ // Unmask the signals to make sure we still don't get\n+ // signaled. That would happen if `tcsetpgrp` enqueued the\n+ // signal through the mask -- we would not yet have received it,\n+ // because of the mask.\n+ sigprocmask(SIG_UNBLOCK, &signal_set, NULL);\n_exit(0);\n}\nint wstatus;\n" } ]
Go
Apache License 2.0
google/gvisor
Fixes to TTOU handling in TIOCSPGRP Fixes two issues in TTOU handling while handling TIOCSPGRP on a tty device. fixes #7941; see that issue for details of the bugs. Updates the tests to test the fixed behavior; both tests are verified to fail without the `thread_group.go` fixes.
259,891
06.09.2022 11:14:41
25,200
6840864b0e3edcf2688ba705676144e91c0679b5
experimental xdp dispatcher
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/BUILD", "new_path": "pkg/tcpip/BUILD", "diff": "@@ -66,6 +66,7 @@ deps_test(\n\"//pkg/state/wire\",\n\"//pkg/sync\",\n\"//pkg/waiter\",\n+ \"//pkg/xdp\",\n# Other deps.\n\"@com_github_google_btree//:go_default_library\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/fdbased/BUILD", "new_path": "pkg/tcpip/link/fdbased/BUILD", "diff": "@@ -11,6 +11,7 @@ go_library(\n\"mmap_stub.go\",\n\"mmap_unsafe.go\",\n\"packet_dispatchers.go\",\n+ \"xdp.go\",\n],\nvisibility = [\"//visibility:public\"],\ndeps = [\n@@ -21,6 +22,7 @@ go_library(\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/link/rawfile\",\n\"//pkg/tcpip/stack\",\n+ \"//pkg/xdp\",\n\"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/fdbased/endpoint.go", "new_path": "pkg/tcpip/link/fdbased/endpoint.go", "diff": "package fdbased\nimport (\n- \"errors\"\n\"fmt\"\n\"golang.org/x/sys/unix\"\n@@ -66,12 +65,12 @@ type linkDispatcher interface {\n// dispatching packets from the underlying FD.\ntype PacketDispatchMode int\n-const (\n// BatchSize is the number of packets to write in each syscall. It is 47\n// because when GvisorGSO is in use then a single 65KB TCP segment can get\n// split into 46 segments of 1420 bytes and a single 216 byte segment.\n- BatchSize = 47\n+const BatchSize = 47\n+const (\n// Readv is the default dispatch mode and is the least performant of the\n// dispatch options but the one that is supported by all underlying FD\n// types.\n@@ -227,7 +226,10 @@ type Options struct {\n// AFXDPFD is used with the experimental AF_XDP mode.\n// TODO(b/240191988): Use multiple sockets.\n// TODO(b/240191988): How do we handle the MTU issue?\n- AFXDPFD int\n+ AFXDPFD *int\n+\n+ // InterfaceIndex is the interface index of the underlying device.\n+ InterfaceIndex int\n}\n// fanoutID is used for AF_PACKET based endpoints to enable PACKET_FANOUT\n@@ -295,8 +297,8 @@ func New(opts *Options) (stack.LinkEndpoint, error) {\n}\n}\n- // Increment fanoutID to ensure that we don't re-use the same fanoutID for\n- // the next endpoint.\n+ // Increment fanoutID to ensure that we don't re-use the same fanoutID\n+ // for the next endpoint.\nfid := fanoutID.Add(1)\n// Create per channel dispatchers.\n@@ -320,6 +322,13 @@ func New(opts *Options) (stack.LinkEndpoint, error) {\ne.gsoMaxSize = opts.GSOMaxSize\n}\n}\n+\n+ // TODO(b/240191988): Remove this check once we support\n+ // multiple AF_XDP sockets.\n+ if opts.AFXDPFD != nil {\n+ continue\n+ }\n+\ninboundDispatcher, err := createInboundDispatcher(e, fd, isSocket, fid)\nif err != nil {\nreturn nil, fmt.Errorf(\"createInboundDispatcher(...) = %v\", err)\n@@ -327,6 +336,15 @@ func New(opts *Options) (stack.LinkEndpoint, error) {\ne.inboundDispatchers = append(e.inboundDispatchers, inboundDispatcher)\n}\n+ if opts.AFXDPFD != nil {\n+ fd := *opts.AFXDPFD\n+ inboundDispatcher, err := newAFXDPDispatcher(fd, e, opts.InterfaceIndex)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"newAFXDPDispatcher(%d, %+v) = %v\", fd, e, err)\n+ }\n+ e.inboundDispatchers = append(e.inboundDispatchers, inboundDispatcher)\n+ }\n+\nreturn e, nil\n}\n@@ -385,8 +403,9 @@ func createInboundDispatcher(e *endpoint, fd int, isSocket bool, fID int32) (lin\nif err != nil {\nreturn nil, fmt.Errorf(\"newRecvMMsgDispatcher(%d, %+v) = %v\", fd, e, err)\n}\n- case AFXDP:\n- return nil, errors.New(\"AFXDP not yet implemented\")\n+ case Readv:\n+ default:\n+ return nil, fmt.Errorf(\"unknown dispatch mode %d\", e.packetDispatchMode)\n}\n}\nreturn inboundDispatcher, nil\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/link/fdbased/xdp.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+//go:build (linux && amd64) || (linux && arm64)\n+// +build linux,amd64 linux,arm64\n+\n+package fdbased\n+\n+import (\n+ \"fmt\"\n+\n+ \"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/bufferv2\"\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/link/rawfile\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/xdp\"\n+)\n+\n+// xdpDispatcher utilizes AF_XDP to dispatch incoming packets.\n+//\n+// xdpDispatcher is experimental and should not be used in production.\n+type xdpDispatcher struct {\n+ // stopFd enables the dispatched to be stopped via stop().\n+ stopFd\n+\n+ // ep is the endpoint this dispatcher is attached to.\n+ ep *endpoint\n+\n+ // fd is the AF_XDP socket FD.\n+ fd int\n+\n+ // The following control the AF_XDP socket.\n+ umem *xdp.UMEM\n+ fillQueue *xdp.FillQueue\n+ rxQueue *xdp.RXQueue\n+}\n+\n+func newAFXDPDispatcher(fd int, ep *endpoint, index int) (linkDispatcher, error) {\n+ stopFd, err := newStopFd()\n+ if err != nil {\n+ return nil, err\n+ }\n+ dispatcher := xdpDispatcher{\n+ stopFd: stopFd,\n+ fd: fd,\n+ ep: ep,\n+ }\n+\n+ // Use a 2MB UMEM to match the PACKET_MMAP dispatcher.\n+ opts := xdp.DefaultReadOnlyOpts()\n+ opts.NFrames = (1 << 21) / opts.FrameSize\n+ dispatcher.umem, dispatcher.fillQueue, dispatcher.rxQueue, err = xdp.ReadOnlyFromSocket(fd, uint32(index), 0 /* queueID */, opts)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"failed to create AF_XDP dispatcher: %v\", err)\n+ }\n+ dispatcher.fillQueue.FillAll()\n+ return &dispatcher, nil\n+}\n+\n+func (xd *xdpDispatcher) dispatch() (bool, tcpip.Error) {\n+ for {\n+ stopped, errno := rawfile.BlockingPollUntilStopped(xd.efd, xd.fd, unix.POLLIN|unix.POLLERR)\n+ if errno != 0 {\n+ if errno == unix.EINTR {\n+ continue\n+ }\n+ return !stopped, rawfile.TranslateErrno(errno)\n+ }\n+ if stopped {\n+ return true, nil\n+ }\n+\n+ // Avoid the cost of the poll syscall if possible by peeking\n+ // until there are no packets left.\n+ for {\n+ xd.fillQueue.FillAll()\n+\n+ // We can receive multiple packets at once.\n+ nReceived, rxIndex := xd.rxQueue.Peek()\n+\n+ if nReceived == 0 {\n+ break\n+ }\n+\n+ for i := uint32(0); i < nReceived; i++ {\n+ // Copy packet bytes into a view and free up the\n+ // buffer.\n+ descriptor := xd.rxQueue.Get(rxIndex + i)\n+ data := xd.umem.Get(descriptor)\n+ view := bufferv2.NewView(int(descriptor.Len))\n+ view.Write(data)\n+ xd.umem.FreeFrame(descriptor.Addr)\n+\n+ // Determine the network protocol.\n+ var netProto tcpip.NetworkProtocolNumber\n+ if xd.ep.hdrSize > 0 {\n+ netProto = header.Ethernet(data).Type()\n+ } else {\n+ // We don't get any indication of what the packet is, so try to guess\n+ // if it's an IPv4 or IPv6 packet.\n+ switch header.IPVersion(data) {\n+ case header.IPv4Version:\n+ netProto = header.IPv4ProtocolNumber\n+ case header.IPv6Version:\n+ netProto = header.IPv6ProtocolNumber\n+ default:\n+ return true, nil\n+ }\n+ }\n+\n+ // Wrap the packet in a PacketBuffer and send it up the stack.\n+ pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ Payload: bufferv2.MakeWithView(view),\n+ })\n+ if xd.ep.hdrSize > 0 {\n+ if _, ok := pkt.LinkHeader().Consume(xd.ep.hdrSize); !ok {\n+ panic(fmt.Sprintf(\"LinkHeader().Consume(%d) must succeed\", xd.ep.hdrSize))\n+ }\n+ }\n+ xd.ep.dispatcher.DeliverNetworkPacket(netProto, pkt)\n+ pkt.DecRef()\n+ }\n+ // Tell the kernel that we're done with these packets.\n+ xd.rxQueue.Release(nReceived)\n+ }\n+\n+ return true, nil\n+ }\n+}\n+\n+func (*xdpDispatcher) release() {\n+ // Noop: let the kernel clean up.\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/network.go", "new_path": "runsc/boot/network.go", "diff": "@@ -88,6 +88,7 @@ type Neighbor struct {\n// FDBasedLink configures an fd-based link.\ntype FDBasedLink struct {\nName string\n+ InterfaceIndex int\nMTU int\nAddresses []IPWithPrefix\nRoutes []Route\n@@ -165,7 +166,7 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\nwantFDs += l.NumChannels\n}\nif args.AFXDP {\n- wantFDs++\n+ wantFDs += 4\n}\nif got := len(args.FilePayload.Files); got != wantFDs {\nreturn fmt.Errorf(\"args.FilePayload.Files has %d FDs but we need %d entries based on FDBasedLinks. AFXDP is %t\", got, wantFDs, args.AFXDP)\n@@ -234,15 +235,28 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\n// If AFXDP is enabled, we perform RX via AF_XDP and TX via\n// AF_PACKET.\n- AFXDPFD := -1\n+ var AFXDPFD *int\nif args.AFXDP {\n+ // Get the AF_XDP socket.\noldFD := args.FilePayload.Files[fdOffset].Fd()\nnewFD, err := unix.Dup(int(oldFD))\nif err != nil {\nreturn fmt.Errorf(\"failed to dup AF_XDP fd %v: %v\", oldFD, err)\n}\n- AFXDPFD = newFD\n+ AFXDPFD = &newFD\nfdOffset++\n+\n+ // The parent process sends several other FDs in order\n+ // to keep them open and alive. These are for BPF\n+ // programs and maps that, if closed, will break the\n+ // dispatcher.\n+ for _, fdName := range []string{\"program-fd\", \"sockmap-fd\", \"link-fd\"} {\n+ oldFD := args.FilePayload.Files[fdOffset].Fd()\n+ if _, err := unix.Dup(int(oldFD)); err != nil {\n+ return fmt.Errorf(\"failed to dup %s with FD %d: %v\", fdName, oldFD, err)\n+ }\n+ fdOffset++\n+ }\n}\nmac := tcpip.LinkAddress(link.LinkAddress)\n@@ -259,6 +273,7 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\nGvisorGSOEnabled: link.GvisorGSOEnabled,\nTXChecksumOffload: link.TXChecksumOffload,\nRXChecksumOffload: link.RXChecksumOffload,\n+ InterfaceIndex: link.InterfaceIndex,\n})\nif err != nil {\nreturn err\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/BUILD", "new_path": "runsc/sandbox/BUILD", "diff": "@@ -10,6 +10,9 @@ go_library(\n\"network_unsafe.go\",\n\"sandbox.go\",\n],\n+ embedsrcs = [\n+ \"//runsc/sandbox/bpf:af_xdp_ebpf.o\", # keep\n+ ],\nvisibility = [\n\"//runsc:__subpackages__\",\n],\n@@ -35,6 +38,8 @@ go_library(\n\"//runsc/donation\",\n\"//runsc/specutils\",\n\"@com_github_cenkalti_backoff//:go_default_library\",\n+ \"@com_github_cilium_ebpf//:go_default_library\",\n+ \"@com_github_cilium_ebpf//link:go_default_library\",\n\"@com_github_opencontainers_runtime_spec//specs-go:go_default_library\",\n\"@com_github_syndtr_gocapability//capability:go_default_library\",\n\"@com_github_vishvananda_netlink//:go_default_library\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "runsc/sandbox/bpf/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"bpf_program\")\n+\n+package(licenses = [\"notice\"])\n+\n+bpf_program(\n+ name = \"af_xdp_ebpf\",\n+ src = \"af_xdp.ebpf.c\",\n+ hdrs = [],\n+ bpf_object = \"af_xdp_ebpf.o\",\n+ visibility = [\"//:sandbox\"],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "runsc/sandbox/bpf/af_xdp.ebpf.c", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <linux/bpf.h>\n+\n+#define section(secname) __attribute__((section(secname), used))\n+\n+char __license[] section(\"license\") = \"Apache-2.0\";\n+\n+// Helper functions are defined positionally in <linux/bpf.h>, and their\n+// signatures are scattered throughout the kernel. They can be found via the\n+// defining macro BPF_CALL_[0-5].\n+// TODO(b/240191988): Use vmlinux instead of this.\n+static int (*bpf_redirect_map)(void *bpf_map, __u32 iface_index,\n+ __u64 flags) = (void *)51;\n+\n+struct bpf_map_def {\n+ unsigned int type;\n+ unsigned int key_size;\n+ unsigned int value_size;\n+ unsigned int max_entries;\n+ unsigned int map_flags;\n+};\n+\n+// A map of RX queue number to AF_XDP socket. We only ever use one key: 0.\n+struct bpf_map_def section(\"maps\") sock_map = {\n+ .type = BPF_MAP_TYPE_XSKMAP, // Note: \"XSK\" means AF_XDP socket.\n+ .key_size = sizeof(int),\n+ .value_size = sizeof(int),\n+ .max_entries = 1,\n+};\n+\n+section(\"xdp\") int xdp_prog(struct xdp_md *ctx) {\n+ // Lookup the socket for the current RX queue. Veth devices by default have\n+ // only one RX queue. If one is found, redirect the packet to that socket.\n+ // Otherwise pass it on to the kernel network stack.\n+ //\n+ // TODO: We can support multiple sockets with a fancier hash-based handoff.\n+ return bpf_redirect_map(&sock_map, ctx->rx_queue_index, XDP_PASS);\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/network.go", "new_path": "runsc/sandbox/network.go", "diff": "package sandbox\nimport (\n+ \"bytes\"\n+ _ \"embed\"\n\"fmt\"\n\"net\"\n\"os\"\n@@ -22,6 +24,8 @@ import (\n\"runtime\"\n\"strconv\"\n+ \"github.com/cilium/ebpf\"\n+ \"github.com/cilium/ebpf/link\"\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n\"github.com/vishvananda/netlink\"\n\"golang.org/x/sys/unix\"\n@@ -217,6 +221,7 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, conf *con\nlink := boot.FDBasedLink{\nName: iface.Name,\n+ InterfaceIndex: iface.Index,\nMTU: iface.MTU,\nRoutes: routes,\nTXChecksumOffload: conf.TXChecksumOffload,\n@@ -254,11 +259,11 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, conf *con\n// If enabled, create an RX socket for AF_XDP.\nif conf.AFXDP {\n- xdpSock, err := createSocketXDP(iface)\n+ xdpSockFDs, err := createSocketXDP(iface)\nif err != nil {\nreturn fmt.Errorf(\"failed to create XDP socket: %v\", err)\n}\n- args.FilePayload.Files = append(args.FilePayload.Files, xdpSock)\n+ args.FilePayload.Files = append(args.FilePayload.Files, xdpSockFDs...)\n}\nif link.GSOMaxSize == 0 && conf.GvisorGSO {\n@@ -387,15 +392,80 @@ func createSocket(iface net.Interface, ifaceLink netlink.Link, enableGSO bool, A\nreturn &socketEntry{deviceFile, gsoMaxSize}, nil\n}\n-func createSocketXDP(iface net.Interface) (*os.File, error) {\n+// program is the BPF program to attach to the socket.\n+//\n+//go:embed bpf/af_xdp_ebpf.o\n+var program []byte\n+\n+func createSocketXDP(iface net.Interface) ([]*os.File, error) {\n// Create an XDP socket. The sentry will mmap memory for the various\n// rings and bind to the device.\nfd, err := unix.Socket(unix.AF_XDP, unix.SOCK_RAW, 0)\nif err != nil {\nreturn nil, fmt.Errorf(\"unable to create AF_XDP socket: %v\", err)\n}\n- deviceFile := os.NewFile(uintptr(fd), \"xdp-fd\")\n- return deviceFile, nil\n+\n+ // We also need to, before dropping privileges, attach a program to the\n+ // device and insert our socket into its map.\n+\n+ // Load into the kernel.\n+ spec, err := ebpf.LoadCollectionSpecFromReader(bytes.NewReader(program))\n+ if err != nil {\n+ return nil, fmt.Errorf(\"failed to load spec: %v\", err)\n+ }\n+\n+ var objects struct {\n+ Program *ebpf.Program `ebpf:\"xdp_prog\"`\n+ SockMap *ebpf.Map `ebpf:\"sock_map\"`\n+ }\n+ if err := spec.LoadAndAssign(&objects, nil); err != nil {\n+ return nil, fmt.Errorf(\"failed to load program: %v\", err)\n+ }\n+\n+ rawLink, err := link.AttachRawLink(link.RawLinkOptions{\n+ Program: objects.Program,\n+ Attach: ebpf.AttachXDP,\n+ Target: iface.Index,\n+ // By not setting the Flag field, the kernel will choose the\n+ // fastest mode. In order those are:\n+ // - Offloaded onto the NIC.\n+ // - Running directly in the driver.\n+ // - Generic mode, which works with any NIC/driver but lacks\n+ // much of the XDP performance boost.\n+ })\n+ if err != nil {\n+ return nil, fmt.Errorf(\"failed to attach BPF program: %v\", err)\n+ }\n+\n+ // Insert our AF_XDP socket into the BPF map that dictates where\n+ // packets are redirected to.\n+ key := uint32(0)\n+ val := uint32(fd)\n+ if err := objects.SockMap.Update(&key, &val, 0 /* flags */); err != nil {\n+ return nil, fmt.Errorf(\"failed to insert socket into BPF map: %v\", err)\n+ }\n+\n+ // We need to keep the Program, SockMap, and link FDs open until they\n+ // can be passed to the sandbox process.\n+ progFD, err := unix.Dup(objects.Program.FD())\n+ if err != nil {\n+ return nil, fmt.Errorf(\"failed to dup BPF program: %v\", err)\n+ }\n+ sockMapFD, err := unix.Dup(objects.SockMap.FD())\n+ if err != nil {\n+ return nil, fmt.Errorf(\"failed to dup BPF map: %v\", err)\n+ }\n+ linkFD, err := unix.Dup(rawLink.FD())\n+ if err != nil {\n+ return nil, fmt.Errorf(\"failed to dup BPF link: %v\", err)\n+ }\n+\n+ return []*os.File{\n+ os.NewFile(uintptr(fd), \"xdp-fd\"), // The socket.\n+ os.NewFile(uintptr(progFD), \"program-fd\"), // The XDP program.\n+ os.NewFile(uintptr(sockMapFD), \"sockmap-fd\"), // The XDP map.\n+ os.NewFile(uintptr(linkFD), \"link-fd\"), // The XDP link.\n+ }, nil\n}\n// loopbackLink returns the link with addresses and routes for a loopback\n" } ]
Go
Apache License 2.0
google/gvisor
experimental xdp dispatcher PiperOrigin-RevId: 472509327
259,891
06.09.2022 17:31:22
25,200
ad7b1121d4b81b52c39e4f2ea041144edc1d1067
xdp: use needs-wakeup flag This is recommended in the kernel docs:
[ { "change_type": "MODIFY", "old_path": "pkg/xdp/xdp.go", "new_path": "pkg/xdp/xdp.go", "diff": "@@ -202,11 +202,15 @@ func ReadOnlyFromSocket(sockfd int, ifaceIdx, queueID uint32, opts ReadOnlySocke\nrxQueue.init(off, opts)\naddr := unix.SockaddrXDP{\n+ // XDP_USE_NEED_WAKEUP lets the driver sleep if there is no\n+ // work to do. It will need to be woken by poll. It is expected\n+ // that this improves performance by preventing the driver from\n+ // burning cycles.\n+ //\n// By not setting either XDP_COPY or XDP_ZEROCOPY, we instruct\n// the kernel to use zerocopy if available and then fallback to\n// copy mode.\n- // TODO(b/240191988): Look into whether to use XDP_USE_NEED_WAKEUP.\n- Flags: 0,\n+ Flags: unix.XDP_USE_NEED_WAKEUP,\nIfindex: ifaceIdx,\n// AF_XDP sockets are per device RX queue, although multiple\n// sockets on multiple queues (or devices) can share a single\n" }, { "change_type": "MODIFY", "old_path": "tools/xdp/README.md", "new_path": "tools/xdp/README.md", "diff": "@@ -31,8 +31,11 @@ must also look at [libbpf itself][libbpf] to understand what's really going on.\n## TODO\n-Kernel version < 5.4 has some weird offsets behavior. Just don't run on those\n-machines.\n+- Kernel version < 5.4 has some weird offsets behavior. Just don't run on\n+ those machines.\n+- Implement SHARED, although it looks like we usually run with only 1\n+ dispatcher.\n+- Add a -redirect $fromdev $todev option in order to test fast path.\n[af_xdp_tutorial]: https://github.com/xdp-project/xdp-tutorial/tree/master/advanced03-AF_XDP\n[libbpf]: https://github.com/torvalds/linux/tree/master/tools/testing/selftests/bpf/xsk.c\n" } ]
Go
Apache License 2.0
google/gvisor
xdp: use needs-wakeup flag This is recommended in the kernel docs: https://www.kernel.org/doc/html/latest/networking/af_xdp.html#xdp-use-need-wakeup-bind-flag PiperOrigin-RevId: 472596449
259,950
25.08.2022 10:35:27
-28,800
39e2e5b968fef9ddb786ae74a1ca4a2b105f416e
support set or get tcpsockopt TCP_MAXSEG, TCP_CONGESTION for hostnetwork.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/hostinet/socket.go", "new_path": "pkg/sentry/socket/hostinet/socket.go", "diff": "@@ -406,10 +406,12 @@ func (s *socketOpsCommon) GetSockOpt(t *kernel.Task, level int, name int, optVal\n}\ncase linux.SOL_TCP:\nswitch name {\n- case linux.TCP_NODELAY:\n+ case linux.TCP_NODELAY, linux.TCP_MAXSEG:\noptlen = sizeofInt32\ncase linux.TCP_INFO:\noptlen = linux.SizeOfTCPInfo\n+ case linux.TCP_CONGESTION:\n+ optlen = outLen\n}\n}\n@@ -461,8 +463,10 @@ func (s *socketOpsCommon) SetSockOpt(t *kernel.Task, level int, name int, opt []\n}\ncase linux.SOL_TCP:\nswitch name {\n- case linux.TCP_NODELAY, linux.TCP_INQ:\n+ case linux.TCP_NODELAY, linux.TCP_INQ, linux.TCP_MAXSEG:\noptlen = sizeofInt32\n+ case linux.TCP_CONGESTION:\n+ optlen = len(opt)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/filter/config.go", "new_path": "runsc/boot/filter/config.go", "diff": "@@ -504,6 +504,16 @@ func hostInetFilters() seccomp.SyscallRules {\nseccomp.EqualTo(unix.SOL_TCP),\nseccomp.EqualTo(linux.TCP_INQ),\n},\n+ {\n+ seccomp.MatchAny{},\n+ seccomp.EqualTo(unix.SOL_TCP),\n+ seccomp.EqualTo(linux.TCP_MAXSEG),\n+ },\n+ {\n+ seccomp.MatchAny{},\n+ seccomp.EqualTo(unix.SOL_TCP),\n+ seccomp.EqualTo(linux.TCP_CONGESTION),\n+ },\n},\nunix.SYS_IOCTL: []seccomp.Rule{\n{\n@@ -572,6 +582,18 @@ func hostInetFilters() seccomp.SyscallRules {\nseccomp.MatchAny{},\nseccomp.EqualTo(4),\n},\n+ {\n+ seccomp.MatchAny{},\n+ seccomp.EqualTo(unix.SOL_TCP),\n+ seccomp.EqualTo(linux.TCP_MAXSEG),\n+ seccomp.MatchAny{},\n+ seccomp.EqualTo(4),\n+ },\n+ {\n+ seccomp.MatchAny{},\n+ seccomp.EqualTo(unix.SOL_TCP),\n+ seccomp.EqualTo(linux.TCP_CONGESTION),\n+ },\n{\nseccomp.MatchAny{},\nseccomp.EqualTo(unix.SOL_IP),\n" } ]
Go
Apache License 2.0
google/gvisor
support set or get tcpsockopt TCP_MAXSEG, TCP_CONGESTION for hostnetwork. Signed-off-by: Tan Yifeng <yiftan@163.com>
259,907
06.09.2022 20:17:10
25,200
658ee7f7cf103f89751b70ec357e0c9a85c58d54
Allow dcache=0 in runsc to completely disable dentry caching in gofer.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/gofer.go", "new_path": "pkg/sentry/fsimpl/gofer/gofer.go", "diff": "@@ -113,13 +113,18 @@ type dentryCache struct {\n// SetDentryCacheSize sets the size of the global gofer dentry cache.\nfunc SetDentryCacheSize(size int) {\n- globalDentryCache.mu.Lock()\n- defer globalDentryCache.mu.Unlock()\n- globalDentryCache.maxCachedDentries = uint64(size)\n+ if size < 0 {\n+ return\n+ }\n+ if globalDentryCache != nil {\n+ log.Warningf(\"Global dentry cache has already been initialized. Ignoring subsequent attempt.\")\n+ return\n+ }\n+ globalDentryCache = &dentryCache{maxCachedDentries: uint64(size)}\n}\n// globalDentryCache is a global cache of dentries across all gofers.\n-var globalDentryCache dentryCache\n+var globalDentryCache *dentryCache\n// Valid values for \"trans\" mount option.\nconst transportModeFD = \"fd\"\n@@ -494,13 +499,11 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n}\n// Did the user configure a global dentry cache?\n- globalDentryCache.mu.Lock()\n- if globalDentryCache.maxCachedDentries >= 1 {\n- fs.dentryCache = &globalDentryCache\n+ if globalDentryCache != nil {\n+ fs.dentryCache = globalDentryCache\n} else {\nfs.dentryCache = &dentryCache{maxCachedDentries: defaultMaxCachedDentries}\n}\n- globalDentryCache.mu.Unlock()\nfs.vfsfs.Init(vfsObj, &fstype, fs)\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/flags.go", "new_path": "runsc/config/flags.go", "diff": "@@ -84,7 +84,7 @@ func RegisterFlags(flagSet *flag.FlagSet) {\nflagSet.Bool(\"cgroupfs\", false, \"Automatically mount cgroupfs.\")\nflagSet.Bool(\"ignore-cgroups\", false, \"don't configure cgroups.\")\nflagSet.Int(\"fdlimit\", -1, \"Specifies a limit on the number of host file descriptors that can be open. Applies separately to the sentry and gofer. Note: each file in the sandbox holds more than one host FD open.\")\n- flagSet.Int(\"dcache\", 0, \"Set the global gofer direct cache size. This acts as a coarse-grained control on the number of host FDs simultaneously open by the sentry. If zero, per-mount caches are used.\")\n+ flagSet.Int(\"dcache\", -1, \"Set the global dentry cache size. This acts as a coarse-grained control on the number of host FDs simultaneously open by the sentry. If negative, per-mount caches are used.\")\n// Flags that control sandbox runtime behavior: network related.\nflagSet.Var(networkTypePtr(NetworkSandbox), \"network\", \"specifies which network to use: sandbox (default), host, none. Using network inside the sandbox is more secure because it's isolated from the host network.\")\n" } ]
Go
Apache License 2.0
google/gvisor
Allow dcache=0 in runsc to completely disable dentry caching in gofer. PiperOrigin-RevId: 472621428
259,891
07.09.2022 14:26:18
25,200
3fb884c2b8104dd3c6f75a620a25dd3f4321658f
runsc: add PCAP logging flag Also: PCAP logging was broken, fixed that. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/sniffer/pcap.go", "new_path": "pkg/tcpip/link/sniffer/pcap.go", "diff": "@@ -55,18 +55,20 @@ type pcapPacket struct {\n}\nfunc (p *pcapPacket) MarshalBinary() ([]byte, error) {\n- packetSize := p.packet.Size()\n+ pkt := trimmedClone(p.packet)\n+ defer pkt.DecRef()\n+ packetSize := pkt.Size()\ncaptureLen := p.maxCaptureLen\nif packetSize < captureLen {\ncaptureLen = packetSize\n}\nb := make([]byte, 16+captureLen)\n- binary.BigEndian.PutUint32(b[0:4], uint32(p.timestamp.Unix()))\n- binary.BigEndian.PutUint32(b[4:8], uint32(p.timestamp.Nanosecond()/1000))\n- binary.BigEndian.PutUint32(b[8:12], uint32(captureLen))\n- binary.BigEndian.PutUint32(b[12:16], uint32(packetSize))\n+ binary.LittleEndian.PutUint32(b[0:4], uint32(p.timestamp.Unix()))\n+ binary.LittleEndian.PutUint32(b[4:8], uint32(p.timestamp.Nanosecond()/1000))\n+ binary.LittleEndian.PutUint32(b[8:12], uint32(captureLen))\n+ binary.LittleEndian.PutUint32(b[12:16], uint32(packetSize))\nw := tcpip.SliceWriter(b[16:])\n- for _, v := range p.packet.AsSlices() {\n+ for _, v := range pkt.AsSlices() {\nif captureLen == 0 {\nbreak\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/sniffer/sniffer.go", "new_path": "pkg/tcpip/link/sniffer/sniffer.go", "diff": "@@ -95,7 +95,7 @@ func writePCAPHeader(w io.Writer, maxLen uint32) error {\nif err != nil {\nreturn err\n}\n- return binary.Write(w, binary.BigEndian, pcapHeader{\n+ return binary.Write(w, binary.LittleEndian, pcapHeader{\n// From https://wiki.wireshark.org/Development/LibpcapFileFormat\nMagicNumber: 0xa1b2c3d4,\n@@ -190,17 +190,7 @@ func LogPacket(prefix string, dir Direction, protocol tcpip.NetworkProtocolNumbe\npanic(fmt.Sprintf(\"unrecognized direction: %d\", dir))\n}\n- // Clone the packet buffer to not modify the original.\n- //\n- // We don't clone the original packet buffer so that the new packet buffer\n- // does not have any of its headers set.\n- //\n- // We trim the link headers from the cloned buffer as the sniffer doesn't\n- // handle link headers.\n- buf := pkt.ToBuffer()\n- buf.TrimFront(int64(len(pkt.VirtioNetHeader().Slice())))\n- buf.TrimFront(int64(len(pkt.LinkHeader().Slice())))\n- pkt = stack.NewPacketBuffer(stack.PacketBufferOptions{Payload: buf})\n+ pkt = trimmedClone(pkt)\ndefer pkt.DecRef()\nswitch protocol {\ncase header.IPv4ProtocolNumber:\n@@ -387,3 +377,17 @@ func LogPacket(prefix string, dir Direction, protocol tcpip.NetworkProtocolNumbe\nlog.Infof(\"%s%s %s %s:%d -> %s:%d len:%d id:%04x %s\", prefix, directionPrefix, transName, src, srcPort, dst, dstPort, size, id, details)\n}\n+\n+// trimmedClone clones the packet buffer to not modify the original. It trims\n+// anything before the network header.\n+func trimmedClone(pkt *stack.PacketBuffer) *stack.PacketBuffer {\n+ // We don't clone the original packet buffer so that the new packet buffer\n+ // does not have any of its headers set.\n+ //\n+ // We trim the link headers from the cloned buffer as the sniffer doesn't\n+ // handle link headers.\n+ buf := pkt.ToBuffer()\n+ buf.TrimFront(int64(len(pkt.VirtioNetHeader().Slice())))\n+ buf.TrimFront(int64(len(pkt.LinkHeader().Slice())))\n+ return stack.NewPacketBuffer(stack.PacketBufferOptions{Payload: buf})\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/network.go", "new_path": "runsc/boot/network.go", "diff": "@@ -17,6 +17,7 @@ package boot\nimport (\n\"fmt\"\n\"net\"\n+ \"os\"\n\"runtime\"\n\"strings\"\n@@ -126,6 +127,9 @@ type CreateLinksAndRoutesArgs struct {\nDefaultv6Gateway DefaultRoute\nAFXDP bool\n+\n+ // PCAP indicates that FilePayload also contains a PCAP log file.\n+ PCAP bool\n}\n// IPWithPrefix is an address with its subnet prefix length.\n@@ -168,8 +172,11 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\nif args.AFXDP {\nwantFDs += 4\n}\n+ if args.PCAP {\n+ wantFDs++\n+ }\nif got := len(args.FilePayload.Files); got != wantFDs {\n- return fmt.Errorf(\"args.FilePayload.Files has %d FDs but we need %d entries based on FDBasedLinks. AFXDP is %t\", got, wantFDs, args.AFXDP)\n+ return fmt.Errorf(\"args.FilePayload.Files has %d FDs but we need %d entries based on FDBasedLinks. AFXDP is %t, PCAP is %t\", got, wantFDs, args.AFXDP, args.PCAP)\n}\nvar nicID tcpip.NICID\n@@ -280,7 +287,21 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\n}\n// Wrap linkEP in a sniffer to enable packet logging.\n- sniffEP := sniffer.New(packetsocket.New(linkEP))\n+ var sniffEP stack.LinkEndpoint\n+ if args.PCAP {\n+ newFD, err := unix.Dup(int(args.FilePayload.Files[fdOffset].Fd()))\n+ if err != nil {\n+ return fmt.Errorf(\"failed to dup pcap FD: %v\", err)\n+ }\n+ const packetTruncateSize = 4096\n+ sniffEP, err = sniffer.NewWithWriter(packetsocket.New(linkEP), os.NewFile(uintptr(newFD), \"pcap-file\"), packetTruncateSize)\n+ if err != nil {\n+ return fmt.Errorf(\"failed to create PCAP logger: %v\", err)\n+ }\n+ fdOffset++\n+ } else {\n+ sniffEP = sniffer.New(packetsocket.New(linkEP))\n+ }\nvar qDisc stack.QueueingDiscipline\nswitch link.QDisc {\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/config.go", "new_path": "runsc/config/config.go", "diff": "@@ -106,6 +106,9 @@ type Config struct {\n// LogPackets indicates that all network packets should be logged.\nLogPackets bool `flag:\"log-packets\"`\n+ // PCAP is a file to which network packets should be logged in PCAP format.\n+ PCAP string `flag:\"pcap-log\"`\n+\n// Platform is the platform to run on.\nPlatform string `flag:\"platform\"`\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/flags.go", "new_path": "runsc/config/flags.go", "diff": "@@ -44,6 +44,7 @@ func RegisterFlags(flagSet *flag.FlagSet) {\nflagSet.String(\"panic-log\", \"\", \"file path where panic reports and other Go's runtime messages are written.\")\nflagSet.String(\"coverage-report\", \"\", \"file path where Go coverage reports are written. Reports will only be generated if runsc is built with --collect_code_coverage and --instrumentation_filter Bazel flags.\")\nflagSet.Bool(\"log-packets\", false, \"enable network packet logging.\")\n+ flagSet.String(\"pcap-log\", \"\", \"location of PCAP log file.\")\nflagSet.String(\"debug-log-format\", \"text\", \"log format: text (default), json, or json-k8s.\")\nflagSet.Bool(\"alsologtostderr\", false, \"send log messages to stderr.\")\nflagSet.Bool(\"allow-flag-override\", false, \"allow OCI annotations (dev.gvisor.flag.<name>) to override flags for debugging.\")\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/network.go", "new_path": "runsc/sandbox/network.go", "diff": "@@ -294,6 +294,16 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, conf *con\nargs.FDBasedLinks = append(args.FDBasedLinks, link)\n}\n+ // Pass PCAP log file if present.\n+ if conf.PCAP != \"\" {\n+ args.PCAP = true\n+ pcap, err := os.OpenFile(conf.PCAP, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0664)\n+ if err != nil {\n+ return fmt.Errorf(\"failed to open PCAP file %s: %v\", conf.PCAP, err)\n+ }\n+ args.FilePayload.Files = append(args.FilePayload.Files, pcap)\n+ }\n+\nlog.Debugf(\"Setting up network, config: %+v\", args)\nif err := conn.Call(boot.NetworkCreateLinksAndRoutes, &args, nil); err != nil {\nreturn fmt.Errorf(\"creating links and routes: %w\", err)\n" } ]
Go
Apache License 2.0
google/gvisor
runsc: add PCAP logging flag Also: PCAP logging was broken, fixed that. Fixes #5968. PiperOrigin-RevId: 472812978
259,891
07.09.2022 14:52:35
25,200
7c8624e575d7bf8d24b13530b8d62698c821c9ea
xdp_loader: refactor to use subcommands No change to behavior, just a refactor. Another program (tunnel) is coming, and the code is becoming unwieldy. Impose some structure.
[ { "change_type": "MODIFY", "old_path": "tools/xdp/BUILD", "new_path": "tools/xdp/BUILD", "diff": "@@ -5,7 +5,10 @@ package(licenses = [\"notice\"])\ngo_binary(\nname = \"xdp_loader\",\nsrcs = [\n+ \"drop.go\",\n\"main.go\",\n+ \"pass.go\",\n+ \"tcpdump.go\",\n],\nembedsrcs = [\n\"//tools/xdp/bpf:drop_ebpf.o\", # keep\n@@ -19,8 +22,10 @@ go_binary(\n\"//pkg/tcpip/link/sniffer\",\n\"//pkg/tcpip/stack\",\n\"//pkg/xdp\",\n+ \"//runsc/flag\",\n\"@com_github_cilium_ebpf//:go_default_library\",\n\"@com_github_cilium_ebpf//link:go_default_library\",\n+ \"@com_github_google_subcommands//:go_default_library\",\n\"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/xdp/drop.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package main\n+\n+import (\n+ \"context\"\n+ _ \"embed\"\n+ \"log\"\n+\n+ \"github.com/google/subcommands\"\n+ \"gvisor.dev/gvisor/runsc/flag\"\n+)\n+\n+//go:embed bpf/drop_ebpf.o\n+var dropProgram []byte\n+\n+// DropCommand is a subcommand for dropping packets.\n+type DropCommand struct {\n+ device string\n+ deviceIndex int\n+}\n+\n+// Name implements subcommands.Command.Name.\n+func (*DropCommand) Name() string {\n+ return \"drop\"\n+}\n+\n+// Synopsis implements subcommands.Command.Synopsis.\n+func (*DropCommand) Synopsis() string {\n+ return \"Drop all packets to the kernel network stack.\"\n+}\n+\n+// Usage implements subcommands.Command.Usage.\n+func (*DropCommand) Usage() string {\n+ return \"drop -device <device> or -devidx <device index>\"\n+}\n+\n+// SetFlags implements subcommands.Command.SetFlags.\n+func (pc *DropCommand) SetFlags(fs *flag.FlagSet) {\n+ fs.StringVar(&pc.device, \"device\", \"\", \"which device to attach to\")\n+ fs.IntVar(&pc.deviceIndex, \"devidx\", 0, \"which device to attach to\")\n+}\n+\n+// Execute implements subcommands.Command.Execute.\n+func (pc *DropCommand) Execute(context.Context, *flag.FlagSet, ...interface{}) subcommands.ExitStatus {\n+ if err := runBasicProgram(dropProgram, pc.device, pc.deviceIndex); err != nil {\n+ log.Printf(\"%v\", err)\n+ return subcommands.ExitFailure\n+ }\n+ return subcommands.ExitSuccess\n+}\n" }, { "change_type": "MODIFY", "old_path": "tools/xdp/main.go", "new_path": "tools/xdp/main.go", "diff": "@@ -21,143 +21,86 @@ package main\nimport (\n\"bytes\"\n+ \"context\"\n_ \"embed\"\n- \"errors\"\n- \"flag\"\n\"fmt\"\n\"log\"\n\"net\"\n+ \"os\"\n\"github.com/cilium/ebpf\"\n\"github.com/cilium/ebpf/link\"\n+ \"github.com/google/subcommands\"\n\"golang.org/x/sys/unix\"\n- \"gvisor.dev/gvisor/pkg/bufferv2\"\n- \"gvisor.dev/gvisor/pkg/tcpip/header\"\n- \"gvisor.dev/gvisor/pkg/tcpip/link/sniffer\"\n- \"gvisor.dev/gvisor/pkg/tcpip/stack\"\n- \"gvisor.dev/gvisor/pkg/xdp\"\n+ \"gvisor.dev/gvisor/runsc/flag\"\n)\n-// Flags.\n-var (\n- device = flag.String(\"device\", \"\", \"which device to attach to\")\n- deviceIndex = flag.Int(\"devidx\", 0, \"which device to attach to\")\n- program = flag.String(\"program\", \"\", \"which program to install: one of [pass, drop, tcpdump]\")\n-)\n-\n-// Builtin programs selectable by users.\n-var (\n- //go:embed bpf/pass_ebpf.o\n- pass []byte\n-\n- //go:embed bpf/drop_ebpf.o\n- drop []byte\n-\n- //go:embed bpf/tcpdump_ebpf.o\n- tcpdump []byte\n-)\n-\n-var programs = map[string][]byte{\n- \"pass\": pass,\n- \"drop\": drop,\n- \"tcpdump\": tcpdump,\n-}\n-\nfunc main() {\n- // log.Fatalf skips important defers, so put everythin in the run\n- // function where it can return errors instead.\n- if err := run(); err != nil {\n- log.Fatalf(\"%v\", err)\n- }\n-}\n-\n-func run() error {\n- // Sanity check.\n- for name, prog := range programs {\n- if len(prog) == 0 {\n- panic(fmt.Sprintf(\"the %s program failed to embed\", name))\n- }\n- }\n+ subcommands.Register(new(DropCommand), \"\")\n+ subcommands.Register(new(PassCommand), \"\")\n+ subcommands.Register(new(TcpdumpCommand), \"\")\nflag.Parse()\n-\n- // Get a net device.\n- var iface *net.Interface\n- var err error\n- switch {\n- case *device != \"\" && *deviceIndex != 0:\n- return fmt.Errorf(\"must specify exactly one of -device or -devidx\")\n- case *device != \"\":\n- if iface, err = net.InterfaceByName(*device); err != nil {\n- return fmt.Errorf(\"unknown device %q: %v\", *device, err)\n- }\n- case *deviceIndex != 0:\n- if iface, err = net.InterfaceByIndex(*deviceIndex); err != nil {\n- return fmt.Errorf(\"unknown device with index %d: %v\", *deviceIndex, err)\n- }\n- default:\n- return fmt.Errorf(\"must specify -device or -devidx\")\n+ ctx := context.Background()\n+ os.Exit(int(subcommands.Execute(ctx)))\n}\n- // Choose a program.\n- if *program == \"\" {\n- return fmt.Errorf(\"must specify -program\")\n- }\n- progData, ok := programs[*program]\n- if !ok {\n- return fmt.Errorf(\"unknown program %q\", *program)\n+func runBasicProgram(progData []byte, device string, deviceIndex int) error {\n+ iface, err := getIface(device, deviceIndex)\n+ if err != nil {\n+ return fmt.Errorf(\"%v\", err)\n}\n- // Load into the kernel. Note that this is usually done using bpf2go,\n- // but since we haven't set up that tool we do everything manually.\n+ // Load into the kernel.\nspec, err := ebpf.LoadCollectionSpecFromReader(bytes.NewReader(progData))\nif err != nil {\nreturn fmt.Errorf(\"failed to load spec: %v\", err)\n}\n- // We need to pass a struct with a field of a specific type and tag.\n- var programObject *ebpf.Program\n- var sockmap *ebpf.Map\n- switch *program {\n- case \"pass\", \"drop\":\nvar objects struct {\nProgram *ebpf.Program `ebpf:\"xdp_prog\"`\n}\nif err := spec.LoadAndAssign(&objects, nil); err != nil {\nreturn fmt.Errorf(\"failed to load program: %v\", err)\n}\n- programObject = objects.Program\ndefer func() {\nif err := objects.Program.Close(); err != nil {\n- log.Printf(\"failed to close program: %v\", err)\n+ fmt.Printf(\"failed to close program: %v\", err)\n}\n}()\n- case \"tcpdump\":\n- var objects struct {\n- Program *ebpf.Program `ebpf:\"xdp_prog\"`\n- SockMap *ebpf.Map `ebpf:\"sock_map\"`\n+\n+ cleanup, err := attach(objects.Program, iface)\n+ if err != nil {\n+ return fmt.Errorf(\"failed to attach: %v\", err)\n}\n- if err := spec.LoadAndAssign(&objects, nil); err != nil {\n- return fmt.Errorf(\"failed to load program: %v\", err)\n+ defer cleanup()\n+\n+ waitForever()\n+ return nil\n}\n- programObject = objects.Program\n- sockmap = objects.SockMap\n- defer func() {\n- if err := objects.Program.Close(); err != nil {\n- log.Printf(\"failed to close program: %v\", err)\n+\n+func getIface(device string, deviceIndex int) (*net.Interface, error) {\n+ switch {\n+ case device != \"\" && deviceIndex != 0:\n+ return nil, fmt.Errorf(\"device specified twice\")\n+ case device != \"\":\n+ iface, err := net.InterfaceByName(device)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"unknown device %q: %v\", device, err)\n}\n- if err := objects.SockMap.Close(); err != nil {\n- log.Printf(\"failed to close sock map: %v\", err)\n+ return iface, nil\n+ case deviceIndex != 0:\n+ iface, err := net.InterfaceByIndex(deviceIndex)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"unknown device with index %d: %v\", deviceIndex, err)\n}\n- }()\n+ return iface, nil\ndefault:\n- return fmt.Errorf(\"unknown program %q\", *program)\n+ return nil, fmt.Errorf(\"no device specified\")\n+ }\n}\n- // TODO(b/240191988): It would be nice to automatically detatch\n- // existing XDP programs, although this can be done with iproute2:\n- // $ ip link set dev eth1 xdp off\n-\n+func attach(program *ebpf.Program, iface *net.Interface) (func(), error) {\n// Attach the program to the XDP hook on the device. Fallback from best\n// to worst mode.\nmodes := []struct {\n@@ -169,9 +112,10 @@ func run() error {\n{name: \"generic\", flag: link.XDPGenericMode},\n}\nvar attached link.Link\n+ var err error\nfor _, mode := range modes {\nattached, err = link.AttachXDP(link.XDPOptions{\n- Program: programObject,\n+ Program: program,\nInterface: iface.Index,\nFlags: mode.flag,\n})\n@@ -182,88 +126,14 @@ func run() error {\nlog.Printf(\"failed to attach with mode %q: %v\", mode.name, err)\n}\nif attached == nil {\n- return fmt.Errorf(\"failed to attach program\")\n- }\n- defer attached.Close()\n-\n- // tcpdump requires opening an AF_XDP socket and having a goroutine\n- // listen for packets.\n- if *program == \"tcpdump\" {\n- if err := startTcpdump(iface, sockmap); err != nil {\n- return fmt.Errorf(\"failed to create AF_XDP socket: %v\", err)\n+ return nil, fmt.Errorf(\"failed to attach program\")\n}\n+ return func() { attached.Close() }, nil\n}\n+func waitForever() {\nlog.Printf(\"Successfully attached! Press CTRL-C to quit and remove the program from the device.\")\nfor {\nunix.Pause()\n}\n}\n-\n-func startTcpdump(iface *net.Interface, sockMap *ebpf.Map) error {\n- umem, fillQueue, rxQueue, err := xdp.ReadOnlySocket(\n- uint32(iface.Index), 0 /* queueID */, xdp.DefaultReadOnlyOpts())\n- if err != nil {\n- return fmt.Errorf(\"failed to create socket: %v\", err)\n- }\n-\n- // Insert our AF_XDP socket into the BPF map that dictates where\n- // packets are redirected to.\n- key := uint32(0)\n- val := umem.SockFD()\n- if err := sockMap.Update(&key, &val, 0 /* flags */); err != nil {\n- return fmt.Errorf(\"failed to insert socket into BPF map: %v\", err)\n- }\n- log.Printf(\"updated key %d to value %d\", key, val)\n-\n- // Put as many UMEM buffers into the fill queue as possible.\n- fillQueue.FillAll()\n-\n- go func() {\n- for {\n- pfds := []unix.PollFd{{Fd: int32(umem.SockFD()), Events: unix.POLLIN}}\n- _, err := unix.Poll(pfds, -1)\n- if err != nil {\n- if errors.Is(err, unix.EINTR) {\n- continue\n- }\n- panic(fmt.Sprintf(\"poll failed: %v\", err))\n- }\n-\n- // How many packets did we get?\n- nReceived, rxIndex := rxQueue.Peek()\n- if nReceived == 0 {\n- continue\n- }\n-\n- // Keep the fill queue full.\n- fillQueue.FillAll()\n-\n- // Read packets one-by-one and log them.\n- for i := uint32(0); i < nReceived; i++ {\n- // Wrap the packet in a PacketBuffer.\n- descriptor := rxQueue.Get(rxIndex + i)\n- data := umem.Get(descriptor)\n- pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- Payload: bufferv2.MakeWithData(data[header.EthernetMinimumSize:]),\n- })\n-\n- sniffer.LogPacket(\"\",\n- sniffer.DirectionRecv, // XDP operates only on ingress.\n- header.Ethernet(data).Type(),\n- pkt)\n-\n- // NOTE: the address is always 256 bytes offset\n- // from a page boundary. The kernel masks the\n- // address to the frame size, so this isn't a\n- // problem.\n- //\n- // Note that this limits MTU to 4096-256 bytes.\n- umem.FreeFrame(descriptor.Addr)\n- }\n- rxQueue.Release(nReceived)\n- }\n- }()\n-\n- return nil\n-}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/xdp/pass.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package main\n+\n+import (\n+ \"context\"\n+ _ \"embed\"\n+ \"log\"\n+\n+ \"github.com/google/subcommands\"\n+ \"gvisor.dev/gvisor/runsc/flag\"\n+)\n+\n+//go:embed bpf/pass_ebpf.o\n+var passProgram []byte\n+\n+// PassCommand is a subcommand for passing packets to the kernel network stack.\n+type PassCommand struct {\n+ device string\n+ deviceIndex int\n+}\n+\n+// Name implements subcommands.Command.Name.\n+func (*PassCommand) Name() string {\n+ return \"pass\"\n+}\n+\n+// Synopsis implements subcommands.Command.Synopsis.\n+func (*PassCommand) Synopsis() string {\n+ return \"Pass all packets to the kernel network stack.\"\n+}\n+\n+// Usage implements subcommands.Command.Usage.\n+func (*PassCommand) Usage() string {\n+ return \"pass -device <device> or -devidx <device index>\"\n+}\n+\n+// SetFlags implements subcommands.Command.SetFlags.\n+func (pc *PassCommand) SetFlags(fs *flag.FlagSet) {\n+ fs.StringVar(&pc.device, \"device\", \"\", \"which device to attach to\")\n+ fs.IntVar(&pc.deviceIndex, \"devidx\", 0, \"which device to attach to\")\n+}\n+\n+// Execute implements subcommands.Command.Execute.\n+func (pc *PassCommand) Execute(context.Context, *flag.FlagSet, ...interface{}) subcommands.ExitStatus {\n+ if err := runBasicProgram(passProgram, pc.device, pc.deviceIndex); err != nil {\n+ log.Printf(\"%v\", err)\n+ return subcommands.ExitFailure\n+ }\n+ return subcommands.ExitSuccess\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/xdp/tcpdump.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package main\n+\n+import (\n+ \"bytes\"\n+ \"context\"\n+ _ \"embed\"\n+ \"errors\"\n+ \"fmt\"\n+ \"log\"\n+\n+ \"github.com/cilium/ebpf\"\n+ \"github.com/google/subcommands\"\n+ \"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/bufferv2\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/link/sniffer\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/xdp\"\n+ \"gvisor.dev/gvisor/runsc/flag\"\n+)\n+\n+//go:embed bpf/tcpdump_ebpf.o\n+var tcpdumpProgram []byte\n+\n+// TcpdumpCommand is a subcommand for capturing incoming packets.\n+type TcpdumpCommand struct {\n+ device string\n+ deviceIndex int\n+}\n+\n+// Name implements subcommands.Command.Name.\n+func (*TcpdumpCommand) Name() string {\n+ return \"tcpdump\"\n+}\n+\n+// Synopsis implements subcommands.Command.Synopsis.\n+func (*TcpdumpCommand) Synopsis() string {\n+ return \"Run tcpdump-like program that blocks incoming packets.\"\n+}\n+\n+// Usage implements subcommands.Command.Usage.\n+func (*TcpdumpCommand) Usage() string {\n+ return \"tcpdump -device <device> or -devidx <device index>\"\n+}\n+\n+// SetFlags implements subcommands.Command.SetFlags.\n+func (pc *TcpdumpCommand) SetFlags(fs *flag.FlagSet) {\n+ fs.StringVar(&pc.device, \"device\", \"\", \"which device to attach to\")\n+ fs.IntVar(&pc.deviceIndex, \"devidx\", 0, \"which device to attach to\")\n+}\n+\n+// Execute implements subcommands.Command.Execute.\n+func (pc *TcpdumpCommand) Execute(context.Context, *flag.FlagSet, ...interface{}) subcommands.ExitStatus {\n+ if err := pc.execute(); err != nil {\n+ fmt.Printf(\"%v\", err)\n+ return subcommands.ExitFailure\n+ }\n+ return subcommands.ExitSuccess\n+}\n+\n+func (pc *TcpdumpCommand) execute() error {\n+ iface, err := getIface(pc.device, pc.deviceIndex)\n+ if err != nil {\n+ return fmt.Errorf(\"%v\", err)\n+ }\n+\n+ // Load into the kernel.\n+ spec, err := ebpf.LoadCollectionSpecFromReader(bytes.NewReader(tcpdumpProgram))\n+ if err != nil {\n+ return fmt.Errorf(\"failed to load spec: %v\", err)\n+ }\n+\n+ var objects struct {\n+ Program *ebpf.Program `ebpf:\"xdp_prog\"`\n+ SockMap *ebpf.Map `ebpf:\"sock_map\"`\n+ }\n+ if err := spec.LoadAndAssign(&objects, nil); err != nil {\n+ return fmt.Errorf(\"failed to load program: %v\", err)\n+ }\n+ defer func() {\n+ if err := objects.Program.Close(); err != nil {\n+ log.Printf(\"failed to close program: %v\", err)\n+ }\n+ if err := objects.SockMap.Close(); err != nil {\n+ log.Printf(\"failed to close sock map: %v\", err)\n+ }\n+ }()\n+\n+ cleanup, err := attach(objects.Program, iface)\n+ if err != nil {\n+ return fmt.Errorf(\"failed to attach: %v\", err)\n+ }\n+ defer cleanup()\n+\n+ umem, fillQueue, rxQueue, err := xdp.ReadOnlySocket(\n+ uint32(iface.Index), 0 /* queueID */, xdp.DefaultReadOnlyOpts())\n+ if err != nil {\n+ return fmt.Errorf(\"failed to create socket: %v\", err)\n+ }\n+\n+ // Insert our AF_XDP socket into the BPF map that dictates where\n+ // packets are redirected to.\n+ key := uint32(0)\n+ val := umem.SockFD()\n+ if err := objects.SockMap.Update(&key, &val, 0 /* flags */); err != nil {\n+ return fmt.Errorf(\"failed to insert socket into BPF map: %v\", err)\n+ }\n+ log.Printf(\"updated key %d to value %d\", key, val)\n+\n+ // Put as many UMEM buffers into the fill queue as possible.\n+ fillQueue.FillAll()\n+\n+ go func() {\n+ for {\n+ pfds := []unix.PollFd{{Fd: int32(umem.SockFD()), Events: unix.POLLIN}}\n+ _, err := unix.Poll(pfds, -1)\n+ if err != nil {\n+ if errors.Is(err, unix.EINTR) {\n+ continue\n+ }\n+ panic(fmt.Sprintf(\"poll failed: %v\", err))\n+ }\n+\n+ // How many packets did we get?\n+ nReceived, rxIndex := rxQueue.Peek()\n+ if nReceived == 0 {\n+ continue\n+ }\n+\n+ // Keep the fill queue full.\n+ fillQueue.FillAll()\n+\n+ // Read packets one-by-one and log them.\n+ for i := uint32(0); i < nReceived; i++ {\n+ // Wrap the packet in a PacketBuffer.\n+ descriptor := rxQueue.Get(rxIndex + i)\n+ data := umem.Get(descriptor)\n+ pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ Payload: bufferv2.MakeWithData(data[header.EthernetMinimumSize:]),\n+ })\n+\n+ sniffer.LogPacket(\"\",\n+ sniffer.DirectionRecv, // XDP operates only on ingress.\n+ header.Ethernet(data).Type(),\n+ pkt)\n+\n+ // NOTE: the address is always 256 bytes offset\n+ // from a page boundary. The kernel masks the\n+ // address to the frame size, so this isn't a\n+ // problem.\n+ //\n+ // Note that this limits MTU to 4096-256 bytes.\n+ umem.FreeFrame(descriptor.Addr)\n+ }\n+ rxQueue.Release(nReceived)\n+ }\n+ }()\n+\n+ waitForever()\n+ return nil\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
xdp_loader: refactor to use subcommands No change to behavior, just a refactor. Another program (tunnel) is coming, and the code is becoming unwieldy. Impose some structure. PiperOrigin-RevId: 472818768
259,853
07.09.2022 15:26:00
25,200
d9556a543f570e21260c4d516d325c4c7bc7e933
kvm: handle a case when a bounce interrupt is triggred in gr0 We disable interrupts in gr0, but go-runtime can resume a routine that has been suspend in hr3. In this case, it restores eflags with the IF flag.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/bluepill_amd64.go", "new_path": "pkg/sentry/platform/kvm/bluepill_amd64.go", "diff": "@@ -128,10 +128,11 @@ func (c *vCPU) KernelSyscall() {\nfunc (c *vCPU) KernelException(vector ring0.Vector) {\nregs := c.Registers()\nif vector == ring0.Vector(bounce) {\n- // These should not interrupt kernel execution; point the Rip\n- // to zero to ensure that we get a reasonable panic when we\n- // attempt to return and a full stack trace.\n- regs.Rip = 0\n+ // This go-routine was saved in hr3 and resumed in gr0 with the\n+ // userspace flags. Let's adjust flags and skip the interrupt.\n+ regs.Eflags &^= uint64(ring0.KernelFlagsClear)\n+ regs.Eflags |= ring0.KernelFlagsSet\n+ return\n}\n// See above.\nring0.HaltAndWriteFSBase(regs) // escapes: no, reload host segment.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go", "new_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go", "diff": "@@ -221,7 +221,6 @@ func bluepillHandler(context unsafe.Pointer) {\nc.die(bluepillArchContext(context), \"entry failed\")\nreturn\ndefault:\n- printHex([]byte(\"exitReason=\"), uint64(c.runData.exitReason))\nbluepillArchHandleExit(c, context)\nreturn\n}\n" } ]
Go
Apache License 2.0
google/gvisor
kvm: handle a case when a bounce interrupt is triggred in gr0 We disable interrupts in gr0, but go-runtime can resume a routine that has been suspend in hr3. In this case, it restores eflags with the IF flag. PiperOrigin-RevId: 472826101
259,950
03.09.2022 09:38:20
-28,800
c844c84a71eff9af18b494c73542b5a231070cd6
Truncate the output buffer to outLen size when getsockopt with TCP_INFO.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/hostinet/socket.go", "new_path": "pkg/sentry/socket/hostinet/socket.go", "diff": "@@ -410,6 +410,10 @@ func (s *socketOpsCommon) GetSockOpt(t *kernel.Task, level int, name int, optVal\noptlen = sizeofInt32\ncase linux.TCP_INFO:\noptlen = linux.SizeOfTCPInfo\n+ // Truncate the output buffer to outLen size.\n+ if optlen > outLen {\n+ optlen = outLen\n+ }\ncase linux.TCP_CONGESTION:\noptlen = outLen\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Truncate the output buffer to outLen size when getsockopt with TCP_INFO. Signed-off-by: Tan Yifeng <yiftan@163.com>
259,907
08.09.2022 10:45:11
25,200
d8b11367560a67c404fc0d3fe67c468c7f339338
Disable process_vm_read_write tests on Linux. These tests are flaky and are blocking submits.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -1066,5 +1066,7 @@ syscall_test(\nsyscall_test(\nsize = \"small\",\n+ # TODO(b/245647342): These tests are flaky on native.\n+ allow_native = False,\ntest = \"//test/syscalls/linux:process_vm_read_write\",\n)\n" } ]
Go
Apache License 2.0
google/gvisor
Disable process_vm_read_write tests on Linux. These tests are flaky and are blocking submits. PiperOrigin-RevId: 473029748
259,853
08.09.2022 14:35:37
25,200
f7855b28f0aa976b7b80778eac6b2b07510e8126
kvm: don't call panic from signal handlers throw has to be used in such cases.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine.go", "new_path": "pkg/sentry/platform/kvm/machine.go", "diff": "@@ -380,13 +380,13 @@ func (m *machine) mapPhysical(physical, length uintptr, phyRegions []physicalReg\n_, physicalStart, length, pr := calculateBluepillFault(physical, phyRegions)\nif pr == nil {\n// Should never happen.\n- panic(\"mapPhysical on unknown physical address\")\n+ throw(\"mapPhysical on unknown physical address\")\n}\n// Is this already mapped? Check the usedSlots.\nif !m.hasSlot(physicalStart) {\nif _, ok := handleBluepillFault(m, physical, phyRegions); !ok {\n- panic(\"handleBluepillFault failed\")\n+ throw(\"handleBluepillFault failed\")\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
kvm: don't call panic from signal handlers throw has to be used in such cases. PiperOrigin-RevId: 473087177
259,907
09.09.2022 08:51:36
25,200
5819462d8f03850f786fb879e70fa7802cad5da1
Add support for O_SYNC and O_DSYNC in gofer client specialFileFD.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/special_file.go", "new_path": "pkg/sentry/fsimpl/gofer/special_file.go", "diff": "@@ -341,6 +341,16 @@ func (fd *specialFileFD) pwrite(ctx context.Context, src usermem.IOSequence, off\nrw := getHandleReadWriter(ctx, &fd.handle, offset)\nn, err := src.CopyInTo(ctx, rw)\nputHandleReadWriter(rw)\n+ if n > 0 && fd.vfsfd.StatusFlags()&(linux.O_DSYNC|linux.O_SYNC) != 0 {\n+ // Note that if syncing the remote file fails, then we can't guarantee that\n+ // any data was actually written with the semantics of O_DSYNC or\n+ // O_SYNC, so we return zero bytes written. Compare Linux's\n+ // mm/filemap.c:generic_file_write_iter() =>\n+ // include/linux/fs.h:generic_write_sync().\n+ if err := fd.sync(ctx, false /* forFilesystemSync */); err != nil {\n+ return 0, offset, err\n+ }\n+ }\nif linuxerr.Equals(linuxerr.EAGAIN, err) {\nerr = linuxerr.ErrWouldBlock\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add support for O_SYNC and O_DSYNC in gofer client specialFileFD. PiperOrigin-RevId: 473263144
259,907
09.09.2022 11:04:26
25,200
ecda533559da3651c3d2746b34bcef53422147f5
Cleanup socket in lisafs gofer's BindAt handler on error paths. Otherwise, we leak will leak the un-closed FD.
[ { "change_type": "MODIFY", "old_path": "runsc/fsgofer/lisafs.go", "new_path": "runsc/fsgofer/lisafs.go", "diff": "@@ -690,12 +690,14 @@ func (fd *controlFDLisa) BindAt(name string, sockType uint32) (*lisafs.ControlFD\nreturn nil, linux.Statx{}, nil, -1, err\n}\nif err := unix.Bind(sockFD, &unix.SockaddrUnix{Name: socketPath}); err != nil {\n+ _ = unix.Close(sockFD)\nreturn nil, linux.Statx{}, nil, -1, err\n}\n// Stat the socket.\nsockStat, err := fstatTo(sockFD)\nif err != nil {\n+ _ = unix.Close(sockFD)\n_ = unix.Unlink(socketPath)\nreturn nil, linux.Statx{}, nil, -1, err\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Cleanup socket in lisafs gofer's BindAt handler on error paths. Otherwise, we leak will leak the un-closed FD. PiperOrigin-RevId: 473294586
259,848
09.09.2022 18:07:00
25,200
31d8668e5178c34343f26020748050a0434419dc
Pseudo-filesystem iouringfs for IO_URING. Similar to Linux, we should add pseudo-filesystem iouringfs in gVisor to back IO_URING's file descriptors. We start with stubbing `io_uring_setup(2)` so it provides a file descriptor backed by anonfs.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/BUILD", "new_path": "pkg/abi/linux/BUILD", "diff": "@@ -35,6 +35,7 @@ go_library(\n\"inotify.go\",\n\"ioctl.go\",\n\"ioctl_tun.go\",\n+ \"iouring.go\",\n\"ip.go\",\n\"ipc.go\",\n\"limits.go\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/abi/linux/iouring.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package linux\n+\n+// Constants for io_uring_setup(2). See include/uapi/linux/io_uring.h.\n+const (\n+ IORING_SETUP_IOPOLL = (1 << 0)\n+ IORING_SETUP_SQPOLL = (1 << 1)\n+ IORING_SETUP_SQ_AFF = (1 << 2)\n+ IORING_SETUP_CQSIZE = (1 << 3)\n+ IORING_SETUP_CLAMP = (1 << 4)\n+ IORING_SETUP_ATTACH_WQ = (1 << 5)\n+ IORING_SETUP_R_DISABLED = (1 << 6)\n+ IORING_SETUP_SUBMIT_ALL = (1 << 7)\n+)\n+\n+// Constants for IO_URING. See include/uapi/linux/io_uring.h.\n+const (\n+ IORING_SETUP_COOP_TASKRUN = (1 << 8)\n+ IORING_SETUP_TASKRUN_FLAG = (1 << 9)\n+ IORING_SETUP_SQE128 = (1 << 10)\n+ IORING_SETUP_CQE32 = (1 << 11)\n+)\n+\n+// Constants for IO_URING. See io_uring/io_uring.c.\n+const (\n+ IORING_MAX_ENTRIES = (1 << 15) // 32768\n+)\n+\n+// IoSqringOffsets implements io_sqring_offsets struct.\n+// See include/uapi/linux/io_uring.h.\n+//\n+// +marshal\n+type IoSqringOffsets struct {\n+ Head uint32\n+ Tail uint32\n+ RingMask uint32\n+ RingEntries uint32\n+ Flags uint32\n+ Dropped uint32\n+ Array uint32\n+ Resv1 uint32\n+ Resv2 uint64\n+}\n+\n+// IoCqringOffsets implements io_cqring_offsets struct.\n+// See include/uapi/linux/io_uring.h.\n+//\n+// +marshal\n+type IoCqringOffsets struct {\n+ Head uint32\n+ Tail uint32\n+ RingMask uint32\n+ RingEntries uint32\n+ Overflow uint32\n+ Cqes uint32\n+ Flags uint32\n+ Resv1 uint32\n+ Resv2 uint64\n+}\n+\n+// IoUringParams implements io_uring_params struct.\n+// See include/uapi/linux/io_uring.h.\n+//\n+// +marshal\n+type IoUringParams struct {\n+ SqEntries uint32\n+ CqEntries uint32\n+ Flags uint32\n+ SqThreadCPU uint32\n+ SqThreadIdle uint32\n+ Features uint32\n+ WqFd uint32\n+ Resv [3]uint32\n+ SqOff IoSqringOffsets\n+ CqOff IoCqringOffsets\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/iouringfs/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+licenses([\"notice\"])\n+\n+go_library(\n+ name = \"iouringfs\",\n+ srcs = [\"iouringfs.go\"],\n+ visibility = [\"//pkg/sentry:internal\"],\n+ deps = [\n+ \"//pkg/abi/linux\",\n+ \"//pkg/context\",\n+ \"//pkg/hostarch\",\n+ \"//pkg/sentry/vfs\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/iouringfs/iouringfs.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package iouringfs provides a filesystem implementation for IO_URING basing\n+// it on anonfs.\n+package iouringfs\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/hostarch\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+)\n+\n+// IoUring implements io_uring struct. See io_uring/io_uring.c.\n+type IoUring struct {\n+ head uint32\n+ tail uint32\n+}\n+\n+// IoUringCqe implements IO completion data structure (Completion Queue Entry)\n+// io_uring_cqe struct. See include/uapi/linux/io_uring.h.\n+type IoUringCqe struct {\n+ userData uint64\n+ res int16\n+ flags uint32\n+ bigCqe *uint64\n+}\n+\n+// FileDescription implements vfs.FileDescriptionImpl for file-based IO_URING.\n+// It is based on io_rings struct. See io_uring/io_uring.c.\n+//\n+// +stateify savable\n+type FileDescription struct {\n+ vfsfd vfs.FileDescription\n+ vfs.FileDescriptionDefaultImpl\n+ vfs.DentryMetadataFileDescriptionImpl\n+ vfs.NoLockFD\n+}\n+\n+var _ vfs.FileDescriptionImpl = (*FileDescription)(nil)\n+\n+// New creates a new iouring fd.\n+func New(ctx context.Context, vfsObj *vfs.VirtualFilesystem, entries uint32, params *linux.IoUringParams, paramsUser hostarch.Addr) (*vfs.FileDescription, error) {\n+ vd := vfsObj.NewAnonVirtualDentry(\"[io_uring]\")\n+ defer vd.DecRef(ctx)\n+\n+ iouringfd := &FileDescription{}\n+\n+ // iouringfd is always set up with read/write mode.\n+ // See io_uring/io_uring.c:io_uring_install_fd().\n+ if err := iouringfd.vfsfd.Init(iouringfd, uint32(linux.O_RDWR), vd.Mount(), vd.Dentry(), &vfs.FileDescriptionOptions{\n+ UseDentryMetadata: true,\n+ DenyPRead: true,\n+ DenyPWrite: true,\n+ DenySpliceIn: true,\n+ }); err != nil {\n+ return nil, err\n+ }\n+\n+ return &iouringfd.vfsfd, nil\n+}\n+\n+// Release implements vfs.FileDescriptionImpl.Release.\n+func (iouringfd *FileDescription) Release(context.Context) {\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/BUILD", "new_path": "pkg/sentry/syscalls/linux/vfs2/BUILD", "diff": "@@ -15,6 +15,7 @@ go_library(\n\"getdents.go\",\n\"inotify.go\",\n\"ioctl.go\",\n+ \"iouringfs.go\",\n\"lock.go\",\n\"memfd.go\",\n\"mmap.go\",\n@@ -54,6 +55,7 @@ go_library(\n\"//pkg/sentry/fsbridge\",\n\"//pkg/sentry/fsimpl/eventfd\",\n\"//pkg/sentry/fsimpl/host\",\n+ \"//pkg/sentry/fsimpl/iouringfs\",\n\"//pkg/sentry/fsimpl/pipefs\",\n\"//pkg/sentry/fsimpl/signalfd\",\n\"//pkg/sentry/fsimpl/timerfd\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/syscalls/linux/vfs2/iouringfs.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package vfs2\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n+ \"gvisor.dev/gvisor/pkg/sentry/arch\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/iouringfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+)\n+\n+// IoUringSetup implements linux syscall io_uring_setup(2).\n+func IoUringSetup(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ entries := uint32(args[0].Uint())\n+ paramsAddr := args[1].Pointer()\n+ var params linux.IoUringParams\n+ if _, err := params.CopyIn(t, paramsAddr); err != nil {\n+ return 0, nil, err\n+ }\n+\n+ for i := int(0); i < len(params.Resv); i++ {\n+ if params.Resv[i] != 0 {\n+ return 0, nil, linuxerr.EINVAL\n+ }\n+ }\n+\n+ vfsObj := t.Kernel().VFS()\n+ iouringfd, err := iouringfs.New(t, vfsObj, entries, &params, paramsAddr)\n+\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+ defer iouringfd.DecRef(t)\n+\n+ fd, err := t.NewFDFromVFS2(0, iouringfd, kernel.FDFlags{\n+ // O_CLOEXEC is always set up. See io_uring/io_uring.c:io_uring_install_fd().\n+ CloseOnExec: true,\n+ })\n+\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+\n+ return uintptr(fd), nil, nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/vfs2.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/vfs2.go", "diff": "@@ -163,6 +163,7 @@ func Override() {\ns.Table[327] = syscalls.Supported(\"preadv2\", Preadv2)\ns.Table[328] = syscalls.Supported(\"pwritev2\", Pwritev2)\ns.Table[332] = syscalls.Supported(\"statx\", Statx)\n+ s.Table[425] = syscalls.PartiallySupported(\"io_uring_setup\", IoUringSetup, \"Not all flags and functionality supported.\", nil)\ns.Table[436] = syscalls.Supported(\"close_range\", CloseRange)\ns.Table[439] = syscalls.Supported(\"faccessat2\", Faccessat2)\ns.Table[441] = syscalls.Supported(\"epoll_pwait2\", EpollPwait2)\n@@ -279,6 +280,7 @@ func Override() {\ns.Table[286] = syscalls.Supported(\"preadv2\", Preadv2)\ns.Table[287] = syscalls.Supported(\"pwritev2\", Pwritev2)\ns.Table[291] = syscalls.Supported(\"statx\", Statx)\n+ s.Table[425] = syscalls.PartiallySupported(\"io_uring_setup\", IoUringSetup, \"Not all flags and functionality supported.\", nil)\ns.Table[436] = syscalls.Supported(\"close_range\", CloseRange)\ns.Table[439] = syscalls.Supported(\"faccessat2\", Faccessat2)\ns.Table[441] = syscalls.Supported(\"epoll_pwait2\", EpollPwait2)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -246,6 +246,10 @@ syscall_test(\ntest = \"//test/syscalls/linux:ioctl_test\",\n)\n+syscall_test(\n+ test = \"//test/syscalls/linux:iouring_test\",\n+)\n+\nsyscall_test(\ntest = \"//test/syscalls/linux:iptables_test\",\n)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -1044,6 +1044,25 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"iouring_test\",\n+ testonly = 1,\n+ srcs = [\"io_uring.cc\"],\n+ linkstatic = 1,\n+ deps = [\n+ \"//test/util:capability_util\",\n+ \"//test/util:file_descriptor\",\n+ \"//test/util:fs_util\",\n+ \"@com_google_absl//absl/strings\",\n+ \"@com_google_absl//absl/time\",\n+ gtest,\n+ \"//test/util:io_uring_util\",\n+ \"//test/util:temp_path\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_library(\nname = \"iptables_types\",\ntestonly = 1,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/syscalls/linux/io_uring.cc", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+#include <pthread.h>\n+#include <stdio.h>\n+#include <stdlib.h>\n+#include <string.h>\n+#include <sys/epoll.h>\n+#include <sys/stat.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/util/io_uring_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+TEST(IoUringTest, ValidFD) {\n+ FileDescriptor iouringfd = ASSERT_NO_ERRNO_AND_VALUE(NewIoUringFD(1));\n+}\n+\n+TEST(IoUringTest, SetUp) {\n+ struct io_uring_params params;\n+ memset(&params, 0, sizeof(params));\n+ ASSERT_THAT(IoUringSetup(1, &params), SyscallSucceeds());\n+}\n+\n+TEST(IoUringTest, ParamsNonZeroResv) {\n+ struct io_uring_params params;\n+ memset(&params, 0, sizeof(params));\n+ params.resv[1] = 1;\n+ ASSERT_THAT(IoUringSetup(1, &params), SyscallFailsWithErrno(EINVAL));\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" }, { "change_type": "MODIFY", "old_path": "test/util/BUILD", "new_path": "test/util/BUILD", "diff": "@@ -59,6 +59,17 @@ cc_library(\nhdrs = [\"fuse_util.h\"],\n)\n+cc_library(\n+ name = \"io_uring_util\",\n+ testonly = 1,\n+ hdrs = [\"io_uring_util.h\"],\n+ deps = [\n+ \":file_descriptor\",\n+ \":posix_error\",\n+ \":save_util\",\n+ ],\n+)\n+\ncc_library(\nname = \"proc_util\",\ntestonly = 1,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/util/io_uring_util.h", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#ifndef GVISOR_TEST_UTIL_IOURING_UTIL_H_\n+#define GVISOR_TEST_UTIL_IOURING_UTIL_H_\n+\n+#include <cerrno>\n+#include <cstdint>\n+\n+#include \"test/util/file_descriptor.h\"\n+#include \"test/util/posix_error.h\"\n+#include \"test/util/save_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+#define __NR_io_uring_setup 425\n+\n+struct io_sqring_offsets {\n+ uint32_t head;\n+ uint32_t tail;\n+ uint32_t ring_mask;\n+ uint32_t ring_entries;\n+ uint32_t flags;\n+ uint32_t dropped;\n+ uint32_t array;\n+ uint32_t resv1;\n+ uint32_t resv2;\n+};\n+\n+struct io_cqring_offsets {\n+ uint32_t head;\n+ uint32_t tail;\n+ uint32_t ring_mask;\n+ uint32_t ring_entries;\n+ uint32_t overflow;\n+ uint32_t cqes;\n+ uint64_t resv[2];\n+};\n+\n+struct io_uring_params {\n+ uint32_t sq_entries;\n+ uint32_t cq_entries;\n+ uint32_t flags;\n+ uint32_t sq_thread_cpu;\n+ uint32_t sq_thread_idle;\n+ uint32_t features;\n+ uint32_t resv[4];\n+ struct io_sqring_offsets sq_off;\n+ struct io_cqring_offsets cq_off;\n+};\n+\n+// This is a wrapper for the io_uring_setup(2) system call.\n+inline uint32_t IoUringSetup(uint32_t entries, struct io_uring_params* params) {\n+ return syscall(__NR_io_uring_setup, entries, params);\n+}\n+\n+// Returns a new iouringfd with the given number of entries.\n+inline PosixErrorOr<FileDescriptor> NewIoUringFD(uint32_t entries) {\n+ struct io_uring_params params;\n+ memset(&params, 0, sizeof(params));\n+ uint32_t fd = IoUringSetup(entries, &params);\n+ MaybeSave();\n+ if (fd < 0) {\n+ return PosixError(errno, \"io_uring_setup\");\n+ }\n+ return FileDescriptor(fd);\n+}\n+\n+} // namespace testing\n+} // namespace gvisor\n+\n+#endif // GVISOR_TEST_UTIL_IOURING_UTIL_H_\n" } ]
Go
Apache License 2.0
google/gvisor
Pseudo-filesystem iouringfs for IO_URING. Similar to Linux, we should add pseudo-filesystem iouringfs in gVisor to back IO_URING's file descriptors. We start with stubbing `io_uring_setup(2)` so it provides a file descriptor backed by anonfs. PiperOrigin-RevId: 473384042
259,891
13.09.2022 10:59:03
25,200
d2827e5a92426db6a61e2c8c4f464b1d2a96bc0b
Don't require gcc-multilib to be installed to build BPF
[ { "change_type": "MODIFY", "old_path": "tools/bazeldefs/defs.bzl", "new_path": "tools/bazeldefs/defs.bzl", "diff": "@@ -91,5 +91,5 @@ def bpf_program(name, src, bpf_object, visibility, hdrs):\nsrcs = [src],\nvisibility = visibility,\nouts = [bpf_object],\n- cmd = \"clang -O2 -Wall -Werror -target bpf -c $< -o $@\",\n+ cmd = \"clang -O2 -Wall -Werror -target bpf -c $< -o $@ -I/usr/include/$$(uname -m)-linux-gnu\",\n)\n" } ]
Go
Apache License 2.0
google/gvisor
Don't require gcc-multilib to be installed to build BPF PiperOrigin-RevId: 474067220
259,852
14.09.2022 02:04:05
-28,800
7cc16b41dfa64b2b387466280a8df096abde8f70
Replace bitset with stdlib math/big Sync changes in runc
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -1896,10 +1896,3 @@ go_repository(\nsum = \"h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=\",\nversion = \"v1.2.0\",\n)\n-\n-go_repository(\n- name = \"com_github_bits_and_blooms_bitset\",\n- importpath = \"github.com/bits-and-blooms/bitset\",\n- sum = \"h1:M+/hrU9xlMp7t4TyTDQW97d3tRPVuKFC6zBEK16QnXY=\",\n- version = \"v1.2.1\",\n-)\n" }, { "change_type": "MODIFY", "old_path": "go.mod", "new_path": "go.mod", "diff": "@@ -5,7 +5,6 @@ go 1.17\nrequire (\ngithub.com/BurntSushi/toml v0.3.1\ngithub.com/bazelbuild/rules_go v0.30.0\n- github.com/bits-and-blooms/bitset v1.2.0\ngithub.com/cenkalti/backoff v1.1.1-0.20190506075156-2146c9339422\ngithub.com/containerd/cgroups v1.0.1\ngithub.com/containerd/console v1.0.1\n" }, { "change_type": "MODIFY", "old_path": "go.sum", "new_path": "go.sum", "diff": "@@ -61,8 +61,6 @@ github.com/bazelbuild/rules_go v0.30.0 h1:kX4jVcstqrsRqKPJSn2mq2o+TI21edRzEJSrEO\ngithub.com/bazelbuild/rules_go v0.30.0/go.mod h1:MC23Dc/wkXEyk3Wpq6lCqz0ZAYOZDw2DR5y3N1q2i7M=\ngithub.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=\ngithub.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=\n-github.com/bits-and-blooms/bitset v1.2.0 h1:Kn4yilvwNtMACtf1eYDlG8H77R07mZSPbMjLyS07ChA=\n-github.com/bits-and-blooms/bitset v1.2.0/go.mod h1:gIdJ4wp64HaoK2YrL1Q5/N7Y16edYb8uY+O0FJTyyDA=\ngithub.com/cenkalti/backoff v1.1.1-0.20190506075156-2146c9339422 h1:8eZxmY1yvxGHzdzTEhI09npjMVGzNAdrqzruTX6jcK4=\ngithub.com/cenkalti/backoff v1.1.1-0.20190506075156-2146c9339422/go.mod h1:b6Nc7NRH5C4aCISLry0tLnTjcuTEvoiqcWDdsU0sOGM=\ngithub.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=\n" }, { "change_type": "MODIFY", "old_path": "runsc/cgroup/BUILD", "new_path": "runsc/cgroup/BUILD", "diff": "@@ -13,7 +13,6 @@ go_library(\ndeps = [\n\"//pkg/cleanup\",\n\"//pkg/log\",\n- \"@com_github_bits_and_blooms_bitset//:go_default_library\",\n\"@com_github_cenkalti_backoff//:go_default_library\",\n\"@com_github_coreos_go_systemd_v22//dbus:go_default_library\",\n\"@com_github_godbus_dbus_v5//:go_default_library\",\n" }, { "change_type": "MODIFY", "old_path": "runsc/cgroup/cgroup_v2.go", "new_path": "runsc/cgroup/cgroup_v2.go", "diff": "@@ -20,18 +20,17 @@ import (\n\"bufio\"\n\"bytes\"\n\"context\"\n- \"encoding/binary\"\n\"errors\"\n\"fmt\"\n\"io/ioutil\"\n\"math\"\n+ \"math/big\"\n\"os\"\n\"path/filepath\"\n\"strconv\"\n\"strings\"\n\"time\"\n- \"github.com/bits-and-blooms/bitset\"\n\"github.com/cenkalti/backoff\"\n\"github.com/coreos/go-systemd/v22/dbus\"\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n@@ -834,7 +833,8 @@ func parseUint(s string, base, bitSize int) (uint64, error) {\n// AllowedCPUs/AllowedMemoryNodes unit property value).\n// Copied from runc.\nfunc RangeToBits(str string) ([]byte, error) {\n- bits := &bitset.BitSet{}\n+ bits := &big.Int{}\n+\nfor _, r := range strings.Split(str, \",\") {\n// allow extra spaces around\nr = strings.TrimSpace(r)\n@@ -855,31 +855,22 @@ func RangeToBits(str string) ([]byte, error) {\nif start > end {\nreturn nil, errors.New(\"invalid range: \" + r)\n}\n- for i := uint(start); i <= uint(end); i++ {\n- bits.Set(i)\n+ for i := start; i <= end; i++ {\n+ bits.SetBit(bits, int(i), 1)\n}\n} else {\nval, err := strconv.ParseUint(ranges[0], 10, 32)\nif err != nil {\nreturn nil, err\n}\n- bits.Set(uint(val))\n+ bits.SetBit(bits, int(val), 1)\n}\n}\n- val := bits.Bytes()\n- if len(val) == 0 {\n+ ret := bits.Bytes()\n+ if len(ret) == 0 {\n// do not allow empty values\nreturn nil, errors.New(\"empty value\")\n}\n- ret := make([]byte, len(val)*8)\n- for i := range val {\n- // bitset uses BigEndian internally\n- binary.BigEndian.PutUint64(ret[i*8:], val[len(val)-1-i])\n- }\n- // remove upper all-zero bytes\n- for ret[0] == 0 {\n- ret = ret[1:]\n- }\nreturn ret, nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Replace bitset with stdlib math/big Sync changes in runc https://github.com/opencontainers/runc/pull/3219
259,891
14.09.2022 10:46:40
25,200
f32046a7cdf175892218ac3e26e1853a7b381022
remove unnecessary dockerfile step After cl/473873880 this is no longer necessary.
[ { "change_type": "MODIFY", "old_path": "images/default/Dockerfile", "new_path": "images/default/Dockerfile", "diff": "@@ -10,9 +10,6 @@ RUN apt-get update && apt-get install -y curl gnupg2 git \\\npkg-config libffi-dev patch diffutils libssl-dev iptables kmod \\\nclang\n-# For compiling BPF with clang.\n-RUN ln -s /usr/include/$(uname -m)-linux-gnu/asm /usr/include/asm\n-\n# Install Docker client for the website build.\nRUN curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -\nRUN add-apt-repository \\\n" } ]
Go
Apache License 2.0
google/gvisor
remove unnecessary dockerfile step After cl/473873880 this is no longer necessary. PiperOrigin-RevId: 474334039
259,856
15.09.2022 08:27:33
14,400
e3774819db8bbff32ee5651c261085c89d2d703e
Adjust typos, grammar, and minor formatting
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/seccheck/README.md", "new_path": "pkg/sentry/seccheck/README.md", "diff": "@@ -72,7 +72,7 @@ message Open {\n}\n```\n-As you can see, come fields are in both raw and schemitized points, like `fd`\n+As you can see, some fields are in both raw and schematized points, like `fd`\nwhich is also `arg1` in the raw syscall, but here it has a name and correct\ntype. It also has fields like `pathname` that are not available in the raw\nsyscall event. In addition, `fd_path` is an optional field that can take the\n@@ -132,21 +132,21 @@ The remote sink serializes the trace point into protobuf and sends it to a\nseparate process. For threat detection, external monitoring processes can\nreceive connections from remote sinks and be sent a stream of trace points that\nare occurring in the system. This sink connects to a remote process via\n-Unix-domain socket and expect the remote process to be listening for new\n-connections. If you're interested about creating a monitoring process that\n+Unix domain socket and expects the remote process to be listening for new\n+connections. If you're interested in creating a monitoring process that\ncommunicates with the remote sink, [this document](sinks/remote/README.md) has\nmore details.\n-The remote sink has many properties that can be configured when its created\n+The remote sink has many properties that can be configured when it's created\n(more on how to configure sinks below):\n-* endpoint (mandatory): Unix-domain socket address to connect.\n-* retries: number of attempts to write the trace point before dropping it in\n+* `endpoint` (mandatory): Unix domain socket address to connect.\n+* `retries`: number of attempts to write the trace point before dropping it in\ncase the remote process is not responding. Note that a high number of\nretries can significantly delay application execution.\n-* backoff: initial backoff time after the first failed attempt. This value\n- doubles every failed attempts up to the max.\n-* backoff_max: max duration to wait between retries.\n+* `backoff`: initial backoff time after the first failed attempt. This value\n+ doubles with every failed attempt, up to the max.\n+* `backoff_max`: max duration to wait between retries.\n## Null\n@@ -164,8 +164,8 @@ points to it.\n# Sessions\n-Trace sessions scope a set of trace point with their corresponding configuration\n-and a set of sinks that receives the points. Sessions can be created at sandbox\n+Trace sessions scope a set of trace points with their corresponding configuration\n+and a set of sinks that receive the points. Sessions can be created at sandbox\ninitialization time or during runtime. Creating sessions at init time guarantees\nthat no trace points are missed, which is important for threat detection. It is\nconfigured using the `--pod-init-config` flag (more on it below). To manage\n@@ -192,7 +192,7 @@ SESSIONS (0)\n## Config\nThe event session can be defined using JSON for the `runsc trace create`\n-command. The session definition has 3 mains parts:\n+command. The session definition has 3 main parts:\n1. `name`: name of the session being created. Only `Default` for now.\n1. `points`: array of points being enabled in the session. Each point has:\n@@ -306,7 +306,7 @@ $ sudo runsc --root /var/run/docker/runtime-runc/moby trace create --config sess\nTrace session \"Default\" created.\n```\n-In the terminal that you are running the monitoring process, you'll start seeing\n+In the terminal where you are running the monitoring process, you'll start seeing\nmessages like this:\n```\n@@ -331,11 +331,11 @@ the parent. The child continues and executes `execve(2)` to call `sleep` as can\nbe seen from the `pathname` and `argv` fields. Note that at this moment, the PID\nis 110 (child) but the process name is still `bash` because it hasn't executed\n`sleep` yet. After `execve(2)` is called the process name changes to `sleep` as\n-expected. Next, it shows the `nanosleep(2)` raw syscalls which has `sysno`=35\n-(it's referred as `syscall/sysno/35` in the configuration file. One for enter\n+expected. Next, it shows the `nanosleep(2)` raw syscalls, which have `sysno`=35\n+(referred to as `syscall/sysno/35` in the configuration file), one for enter\nwith the exit trace happening 5 seconds later.\n-Let's list all trace session that are active in the sandbox:\n+Let's list all trace sessions that are active in the sandbox:\n```shell\n$ sudo runsc --root /var/run/docker/runtime-runc/moby trace list ${CID?}\n" } ]
Go
Apache License 2.0
google/gvisor
Adjust typos, grammar, and minor formatting
259,939
14.09.2022 15:15:50
-28,800
479784577dae05ca16bcdd8092caed52d85d732c
procfs: support /proc/[pid]/root file
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/proc/task.go", "new_path": "pkg/sentry/fs/proc/task.go", "diff": "@@ -114,6 +114,7 @@ func (p *proc) newTaskDir(ctx context.Context, t *kernel.Task, msrc *fs.MountSou\n\"ns\": newNamespaceDir(ctx, t, msrc),\n\"oom_score\": newOOMScore(ctx, msrc),\n\"oom_score_adj\": newOOMScoreAdj(ctx, t, msrc),\n+ \"root\": newRoot(ctx, t, msrc),\n\"smaps\": newSmaps(ctx, t, msrc),\n\"stat\": newTaskStat(ctx, t, msrc, isThreadGroup, p.pidns),\n\"statm\": newStatm(ctx, t, msrc),\n@@ -357,6 +358,49 @@ func (e *cwd) Readlink(ctx context.Context, inode *fs.Inode) (string, error) {\nreturn name, nil\n}\n+// root is an fs.InodeOperations symlink for the /proc/PID/root file.\n+//\n+// +stateify savable\n+type root struct {\n+ ramfs.Symlink\n+\n+ t *kernel.Task\n+}\n+\n+func newRoot(ctx context.Context, t *kernel.Task, msrc *fs.MountSource) *fs.Inode {\n+ rootSymlink := &root{\n+ Symlink: *ramfs.NewSymlink(ctx, fs.RootOwner, \"\"),\n+ t: t,\n+ }\n+ return newProcInode(ctx, rootSymlink, msrc, fs.Symlink, t)\n+}\n+\n+// Readlink implements fs.InodeOperations.\n+func (e *root) Readlink(ctx context.Context, inode *fs.Inode) (string, error) {\n+ if !kernel.ContextCanTrace(ctx, e.t, false) {\n+ return \"\", linuxerr.EACCES\n+ }\n+ if err := checkTaskState(e.t); err != nil {\n+ return \"\", err\n+ }\n+ root := e.t.FSContext().RootDirectory()\n+ if root == nil {\n+ // It could have raced with process deletion.\n+ return \"\", linuxerr.ESRCH\n+ }\n+ defer root.DecRef(ctx)\n+\n+ fsRoot := fs.RootFromContext(ctx)\n+ if fsRoot == nil {\n+ // It could have raced with process deletion.\n+ return \"\", linuxerr.ESRCH\n+ }\n+ defer fsRoot.DecRef(ctx)\n+\n+ name, _ := root.FullName(fsRoot)\n+ return name, nil\n+}\n+\n// namespaceSymlink represents a symlink in the namespacefs, such as the files\n// in /proc/<pid>/ns.\n//\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task.go", "new_path": "pkg/sentry/fsimpl/proc/task.go", "diff": "@@ -76,6 +76,7 @@ func (fs *filesystem) newTaskInode(ctx context.Context, task *kernel.Task, pidns\n}),\n\"oom_score\": fs.newTaskOwnedInode(ctx, task, fs.NextIno(), 0444, newStaticFile(\"0\\n\")),\n\"oom_score_adj\": fs.newTaskOwnedInode(ctx, task, fs.NextIno(), 0644, &oomScoreAdj{task: task}),\n+ \"root\": fs.newRootSymlink(ctx, task, fs.NextIno()),\n\"smaps\": fs.newTaskOwnedInode(ctx, task, fs.NextIno(), 0444, &smapsData{task: task}),\n\"stat\": fs.newTaskOwnedInode(ctx, task, fs.NextIno(), 0444, &taskStatData{task: task, pidns: pidns, tgstats: isThreadGroup}),\n\"statm\": fs.newTaskOwnedInode(ctx, task, fs.NextIno(), 0444, &statmData{task: task}),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task_files.go", "new_path": "pkg/sentry/fsimpl/proc/task_files.go", "diff": "@@ -1035,6 +1035,68 @@ func (s *cwdSymlink) Getlink(ctx context.Context, _ *vfs.Mount) (vfs.VirtualDent\nreturn cwd, \"\", nil\n}\n+// rootSymlink is an symlink for the /proc/[pid]/root file.\n+//\n+// +stateify savable\n+type rootSymlink struct {\n+ implStatFS\n+ kernfs.InodeAttrs\n+ kernfs.InodeNoopRefCount\n+ kernfs.InodeSymlink\n+ kernfs.InodeWatches\n+\n+ fs *filesystem\n+ task *kernel.Task\n+}\n+\n+var _ kernfs.Inode = (*rootSymlink)(nil)\n+\n+func (fs *filesystem) newRootSymlink(ctx context.Context, task *kernel.Task, ino uint64) kernfs.Inode {\n+ inode := &rootSymlink{\n+ fs: fs,\n+ task: task,\n+ }\n+ inode.Init(ctx, task.Credentials(), linux.UNNAMED_MAJOR, fs.devMinor, ino, linux.ModeSymlink|0777)\n+ return inode\n+}\n+\n+// Readlink implements kernfs.Inode.Readlink.\n+func (s *rootSymlink) Readlink(ctx context.Context, _ *vfs.Mount) (string, error) {\n+ root, _, err := s.Getlink(ctx, nil)\n+ if err != nil {\n+ return \"\", err\n+ }\n+ defer s.fs.SafeDecRef(ctx, root)\n+\n+ vfsRoot := vfs.RootFromContext(ctx)\n+ if !vfsRoot.Ok() {\n+ // It could have raced with process deletion.\n+ return \"\", linuxerr.ESRCH\n+ }\n+ defer s.fs.SafeDecRef(ctx, vfsRoot)\n+\n+ vfsObj := root.Mount().Filesystem().VirtualFilesystem()\n+ name, _ := vfsObj.PathnameWithDeleted(ctx, vfsRoot, root)\n+ return name, nil\n+}\n+\n+// Getlink implements kernfs.Inode.Getlink.\n+func (s *rootSymlink) Getlink(ctx context.Context, _ *vfs.Mount) (vfs.VirtualDentry, string, error) {\n+ if !kernel.ContextCanTrace(ctx, s.task, false) {\n+ return vfs.VirtualDentry{}, \"\", linuxerr.EACCES\n+ }\n+ if err := checkTaskState(s.task); err != nil {\n+ return vfs.VirtualDentry{}, \"\", err\n+ }\n+ root := s.task.FSContext().RootDirectoryVFS2()\n+ if !root.Ok() {\n+ // It could have raced with process deletion.\n+ return vfs.VirtualDentry{}, \"\", linuxerr.ESRCH\n+ }\n+ // The reference is transferred to the caller.\n+ return root, \"\", nil\n+}\n+\n// mountInfoData is used to implement /proc/[pid]/mountinfo.\n//\n// +stateify savable\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_test.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_test.go", "diff": "@@ -86,6 +86,7 @@ var (\n\"ns\": linux.DT_DIR,\n\"oom_score\": linux.DT_REG,\n\"oom_score_adj\": linux.DT_REG,\n+ \"root\": linux.DT_LNK,\n\"smaps\": linux.DT_REG,\n\"stat\": linux.DT_REG,\n\"statm\": linux.DT_REG,\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc.cc", "new_path": "test/syscalls/linux/proc.cc", "diff": "@@ -1223,6 +1223,11 @@ TEST(ProcSelfCwd, Absolute) {\nEXPECT_EQ(exe[0], '/');\n}\n+TEST(ProcSelfRoot, Absolute) {\n+ auto exe = ASSERT_NO_ERRNO_AND_VALUE(ReadLink(\"/proc/self/root\"));\n+ EXPECT_EQ(exe[0], '/');\n+}\n+\n// Sanity check that /proc/cmdline is present.\nTEST(ProcCmdline, IsPresent) {\nstd::string proc_cmdline =\n@@ -2018,6 +2023,14 @@ TEST(ProcPidCwd, Subprocess) {\nEXPECT_EQ(got, want);\n}\n+// /proc/PID/root points to the correct directory.\n+TEST(ProcPidRoot, Subprocess) {\n+ char got[PATH_MAX + 1] = {};\n+ ASSERT_THAT(ReadlinkWhileRunning(\"root\", got, sizeof(got)),\n+ SyscallSucceedsWithValue(Gt(0)));\n+ EXPECT_EQ(got, '/');\n+}\n+\n// Test whether /proc/PID/ files can be read for a running process.\nTEST(ProcPidFile, SubprocessRunning) {\nchar buf[1];\n" } ]
Go
Apache License 2.0
google/gvisor
procfs: support /proc/[pid]/root file Signed-off-by: Chen Hui <cedriccchen@tencent.com>
259,962
16.09.2022 15:18:37
25,200
cfc29d3b5dacc8b18acf69b39919afc1756820c5
Add support for block/mutex/trace profiles.
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/tcp/tcp_benchmark.sh", "new_path": "test/benchmarks/tcp/tcp_benchmark.sh", "diff": "@@ -138,6 +138,18 @@ while [ $# -gt 0 ]; do\nshift\nnetstack_opts=\"${netstack_opts} -memprofile=$1\"\n;;\n+ --blockprofile)\n+ shift\n+ netstack_opts=\"${netstack_opts} -blockprofile=$1\"\n+ ;;\n+ --mutexprofile)\n+ shift\n+ netstack_opts=\"${netstack_opts} -mutexprofile=$1\"\n+ ;;\n+ --traceprofile)\n+ shift\n+ netstack_opts=\"${netstack_opts} -traceprofile=$1\"\n+ ;;\n--disable-linux-gso)\ndisable_linux_gso=1\n;;\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/tcp/tcp_proxy.go", "new_path": "test/benchmarks/tcp/tcp_proxy.go", "diff": "@@ -28,6 +28,7 @@ import (\n\"regexp\"\n\"runtime\"\n\"runtime/pprof\"\n+ \"runtime/trace\"\n\"strconv\"\n\"time\"\n@@ -66,6 +67,9 @@ var (\nserverTCPProbeFile = flag.String(\"server_tcp_probe_file\", \"\", \"if specified, installs a tcp probe to dump endpoint state to the specified file.\")\ncpuprofile = flag.String(\"cpuprofile\", \"\", \"write cpu profile to the specified file.\")\nmemprofile = flag.String(\"memprofile\", \"\", \"write memory profile to the specified file.\")\n+ blockprofile = flag.String(\"blockprofile\", \"\", \"write a goroutine blocking profile to the specified file.\")\n+ mutexprofile = flag.String(\"mutexprofile\", \"\", \"write a mutex profile to the specified file.\")\n+ traceprofile = flag.String(\"traceprofile\", \"\", \"write a 5s trace of the benchmark to the specified file.\")\nuseIpv6 = flag.Bool(\"ipv6\", false, \"use ipv6 instead of ipv4.\")\n)\n@@ -212,7 +216,8 @@ func newNetstackImpl(mode string) (impl, error) {\n// regenerate valid checksums after GRO.\nTXChecksumOffload: false,\nRXChecksumOffload: true,\n- PacketDispatchMode: fdbased.RecvMMsg,\n+ //PacketDispatchMode: fdbased.RecvMMsg,\n+ PacketDispatchMode: fdbased.PacketMMap,\nGSOMaxSize: uint32(*gso),\nGvisorGSOEnabled: *swgso,\n})\n@@ -397,6 +402,35 @@ func main() {\ndefer pprof.StopCPUProfile()\n}\n+ if *traceprofile != \"\" {\n+ f, err := os.Create(*traceprofile)\n+ if err != nil {\n+ log.Fatal(\"could not create trace profile: \", err)\n+ }\n+ defer func() {\n+ if err := f.Close(); err != nil {\n+ log.Print(\"error closing trace profile: \", err)\n+ }\n+ }()\n+ go func() {\n+ // Delay tracing to give workload sometime to start.\n+ time.Sleep(2 * time.Second)\n+ if err := trace.Start(f); err != nil {\n+ log.Fatal(\"could not start Go trace:\", err)\n+ }\n+ defer trace.Stop()\n+ <-time.After(5 * time.Second)\n+ }()\n+ }\n+\n+ if *mutexprofile != \"\" {\n+ runtime.SetMutexProfileFraction(100)\n+ }\n+\n+ if *blockprofile != \"\" {\n+ runtime.SetBlockProfileRate(1000)\n+ }\n+\nvar (\nin impl\nout impl\n@@ -468,6 +502,34 @@ func main() {\nlog.Fatalf(\"Unable to write heap profile: %v\", err)\n}\n}\n+ if *blockprofile != \"\" {\n+ f, err := os.Create(*blockprofile)\n+ if err != nil {\n+ log.Fatal(\"could not create block profile: \", err)\n+ }\n+ defer func() {\n+ if err := f.Close(); err != nil {\n+ log.Print(\"error closing block profile: \", err)\n+ }\n+ }()\n+ if err := pprof.Lookup(\"block\").WriteTo(f, 0); err != nil {\n+ log.Fatalf(\"Unable to write block profile: %v\", err)\n+ }\n+ }\n+ if *mutexprofile != \"\" {\n+ f, err := os.Create(*mutexprofile)\n+ if err != nil {\n+ log.Fatal(\"could not create mutex profile: \", err)\n+ }\n+ defer func() {\n+ if err := f.Close(); err != nil {\n+ log.Print(\"error closing mutex profile: \", err)\n+ }\n+ }()\n+ if err := pprof.Lookup(\"mutex\").WriteTo(f, 0); err != nil {\n+ log.Fatalf(\"Unable to write mutex profile: %v\", err)\n+ }\n+ }\nos.Exit(0)\n}()\n" } ]
Go
Apache License 2.0
google/gvisor
Add support for block/mutex/trace profiles. PiperOrigin-RevId: 474912515
259,907
19.09.2022 10:34:40
25,200
72e8fabaecee4bdc08cae623ca52a00c077be944
Add transport.BoundSocketFD interface. This is beneficial for 2 reasons: transport package should not depend on lisafs, which is a user of that package. This allows users other than lisafs client to use transport.HostBoundEndpoint.
[ { "change_type": "MODIFY", "old_path": "pkg/lisafs/client_file.go", "new_path": "pkg/lisafs/client_file.go", "diff": "@@ -573,7 +573,8 @@ func (f *ClientFD) RemoveXattr(ctx context.Context, name string) error {\nreturn err\n}\n-// ClientBoundSocketFD corresponds to a bound socket on the server.\n+// ClientBoundSocketFD corresponds to a bound socket on the server. It\n+// implements transport.BoundSocketFD.\n//\n// All fields are immutable.\ntype ClientBoundSocketFD struct {\n@@ -587,19 +588,18 @@ type ClientBoundSocketFD struct {\nclient *Client\n}\n-// Close closes the host and gofer-backed FDs associated to this bound socket.\n+// Close implements transport.BoundSocketFD.Close.\nfunc (f *ClientBoundSocketFD) Close(ctx context.Context) {\n_ = unix.Close(int(f.notificationFD))\nf.client.CloseFD(ctx, f.fd, true /* flush */)\n}\n-// NotificationFD is a host FD that can be used to notify when new clients\n-// connect to the socket.\n+// NotificationFD implements transport.BoundSocketFD.NotificationFD.\nfunc (f *ClientBoundSocketFD) NotificationFD() int32 {\nreturn f.notificationFD\n}\n-// Listen makes a Listen RPC.\n+// Listen implements transport.BoundSocketFD.Listen.\nfunc (f *ClientBoundSocketFD) Listen(ctx context.Context, backlog int32) error {\nreq := ListenReq{\nFD: f.fd,\n@@ -612,7 +612,7 @@ func (f *ClientBoundSocketFD) Listen(ctx context.Context, backlog int32) error {\nreturn err\n}\n-// Accept makes an Accept RPC.\n+// Accept implements transport.BoundSocketFD.Accept.\nfunc (f *ClientBoundSocketFD) Accept(ctx context.Context) (int, error) {\nreq := AcceptReq{\nFD: f.fd,\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/transport/BUILD", "new_path": "pkg/sentry/socket/unix/transport/BUILD", "diff": "@@ -99,7 +99,6 @@ go_library(\n\"//pkg/errors/linuxerr\",\n\"//pkg/fdnotifier\",\n\"//pkg/ilist\",\n- \"//pkg/lisafs\",\n\"//pkg/log\",\n\"//pkg/refs\",\n\"//pkg/refsvfs2\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/transport/connectioned.go", "new_path": "pkg/sentry/socket/unix/transport/connectioned.go", "diff": "@@ -21,7 +21,6 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fdnotifier\"\n- \"gvisor.dev/gvisor/pkg/lisafs\"\n\"gvisor.dev/gvisor/pkg/sentry/uniqueid\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n@@ -120,7 +119,7 @@ type connectionedEndpoint struct {\n// that may listen and accept incoming connections.\n//\n// boundSocketFD is protected by baseEndpoint.mu.\n- boundSocketFD *lisafs.ClientBoundSocketFD\n+ boundSocketFD BoundSocketFD\n}\nvar (\n@@ -604,7 +603,7 @@ func (e *connectionedEndpoint) OnSetSendBufferSize(v int64) (newSz int64) {\nfunc (e *connectionedEndpoint) WakeupWriters() {}\n// SetBoundSocketFD implement HostBountEndpoint.SetBoundSocketFD.\n-func (e *connectionedEndpoint) SetBoundSocketFD(bsFD *lisafs.ClientBoundSocketFD) {\n+func (e *connectionedEndpoint) SetBoundSocketFD(bsFD BoundSocketFD) {\ne.Lock()\ndefer e.Unlock()\nif e.boundSocketFD != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/transport/unix.go", "new_path": "pkg/sentry/socket/unix/transport/unix.go", "diff": "@@ -18,7 +18,6 @@ package transport\nimport (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n- \"gvisor.dev/gvisor/pkg/lisafs\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n@@ -269,9 +268,26 @@ type BoundEndpoint interface {\n// on the host.\ntype HostBoundEndpoint interface {\n// SetBoundSocketFD will be called on supporting endpoints after\n- // binding a socket on the host filesystem. Implementations should use\n- // delegate Listen and Accept calls to the ClientBoundSocketFD.\n- SetBoundSocketFD(*lisafs.ClientBoundSocketFD)\n+ // binding a socket on the host filesystem. Implementations should\n+ // delegate Listen and Accept calls to the BoundSocketFD.\n+ SetBoundSocketFD(bsFD BoundSocketFD)\n+}\n+\n+// BoundSocketFD is an interface that wraps a socket FD that was bind(2)-ed.\n+// It allows to listen and accept on that socket.\n+type BoundSocketFD interface {\n+ // Close closes the socket FD.\n+ Close(ctx context.Context)\n+\n+ // NotificationFD is a host FD that can be used to notify when new clients\n+ // connect to the socket.\n+ NotificationFD() int32\n+\n+ // Listen is analogous to listen(2).\n+ Listen(ctx context.Context, backlog int32) error\n+\n+ // Accept is analogous to accept(2).\n+ Accept(ctx context.Context) (int, error)\n}\n// message represents a message passed over a Unix domain socket.\n" } ]
Go
Apache License 2.0
google/gvisor
Add transport.BoundSocketFD interface. This is beneficial for 2 reasons: - transport package should not depend on lisafs, which is a user of that package. - This allows users other than lisafs client to use transport.HostBoundEndpoint. PiperOrigin-RevId: 475326947
259,891
19.09.2022 11:42:24
25,200
48e2252b3bacc60b87f7ca36cc6f0d8729b3cb4c
fix panic caused by too-large buffer allocations Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/BUILD", "new_path": "pkg/tcpip/header/BUILD", "diff": "@@ -7,6 +7,7 @@ go_library(\nsrcs = [\n\"arp.go\",\n\"checksum.go\",\n+ \"datagram.go\",\n\"eth.go\",\n\"gue.go\",\n\"icmpv4.go\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/header/datagram.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package header\n+\n+// DatagramMaximumSize is the maximum supported size of a single datagram.\n+const DatagramMaximumSize = 0xffff // 65KB.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/icmp/endpoint.go", "new_path": "pkg/tcpip/transport/icmp/endpoint.go", "diff": "@@ -337,6 +337,11 @@ func (e *endpoint) write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, tcp\n}\ndefer ctx.Release()\n+ // Prevents giant buffer allocations.\n+ if p.Len() > header.DatagramMaximumSize {\n+ return 0, &tcpip.ErrMessageTooLong{}\n+ }\n+\nv := bufferv2.NewView(p.Len())\ndefer v.Release()\nif _, err := io.CopyN(v, p, int64(p.Len())); err != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/packet/endpoint.go", "new_path": "pkg/tcpip/transport/packet/endpoint.go", "diff": "@@ -234,6 +234,11 @@ func (ep *endpoint) Write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, tc\nreturn 0, &tcpip.ErrInvalidOptionValue{}\n}\n+ // Prevents giant buffer allocations.\n+ if p.Len() > header.DatagramMaximumSize {\n+ return 0, &tcpip.ErrMessageTooLong{}\n+ }\n+\nvar payload bufferv2.Buffer\nif _, err := payload.WriteFromReader(p, int64(p.Len())); err != nil {\nreturn 0, &tcpip.ErrBadBuffer{}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/raw/endpoint.go", "new_path": "pkg/tcpip/transport/raw/endpoint.go", "diff": "@@ -350,6 +350,11 @@ func (e *endpoint) write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, tcp\nreturn 0, &tcpip.ErrMessageTooLong{}\n}\n+ // Prevents giant buffer allocations.\n+ if p.Len() > header.DatagramMaximumSize {\n+ return 0, &tcpip.ErrMessageTooLong{}\n+ }\n+\nvar payload bufferv2.Buffer\ndefer payload.Release()\nif _, err := payload.WriteFromReader(p, int64(p.Len())); err != nil {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/ping_socket.cc", "new_path": "test/syscalls/linux/ping_socket.cc", "diff": "@@ -81,6 +81,29 @@ TEST(PingSocket, ICMPPortExhaustion) {\n}\n}\n+TEST(PingSocket, PayloadTooLarge) {\n+ PosixErrorOr<FileDescriptor> result =\n+ Socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP);\n+ if (!result.ok()) {\n+ int errno_value = result.error().errno_value();\n+ ASSERT_EQ(errno_value, EACCES) << strerror(errno_value);\n+ GTEST_SKIP() << \"ping socket not supported\";\n+ }\n+ FileDescriptor& ping = result.ValueOrDie();\n+\n+ constexpr icmphdr kSendIcmp = {\n+ .type = ICMP_ECHO,\n+ };\n+ constexpr size_t kGiantSize = 1 << 21; // 2MB.\n+ const sockaddr_in kAddr = {\n+ .sin_family = AF_INET,\n+ .sin_addr = {.s_addr = htonl(INADDR_LOOPBACK)},\n+ };\n+ ASSERT_THAT(sendto(ping.get(), &kSendIcmp, kGiantSize, 0,\n+ reinterpret_cast<const sockaddr*>(&kAddr), sizeof(kAddr)),\n+ SyscallFailsWithErrno(EMSGSIZE));\n+}\n+\nTEST(PingSocket, ReceiveTOS) {\nPosixErrorOr<FileDescriptor> result =\nSocket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP);\n" } ]
Go
Apache License 2.0
google/gvisor
fix panic caused by too-large buffer allocations Reported-by: syzbot+954128c9aa37e285d23c@syzkaller.appspotmail.com PiperOrigin-RevId: 475345594
259,939
13.09.2022 18:26:53
-28,800
b448cdbed7d92059857930384d4c89324751f501
benchmarks: add syscallbench benchmark for syscall performance
[ { "change_type": "ADD", "old_path": null, "new_path": "images/benchmarks/syscallbench/Dockerfile", "diff": "+FROM ubuntu:18.04\n+\n+RUN set -x \\\n+ && apt-get update \\\n+ && apt-get install -y \\\n+ gcc \\\n+ && rm -rf /var/lib/apt/lists/*\n+\n+COPY ./syscallbench.c /\n+RUN gcc /syscallbench.c -o /usr/bin/syscallbench\n" }, { "change_type": "ADD", "old_path": null, "new_path": "images/benchmarks/syscallbench/syscallbench.c", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <stdio.h>\n+#include <sys/syscall.h>\n+#include <unistd.h>\n+#include <stdlib.h>\n+#include <getopt.h>\n+\n+static int loops = 10000000;\n+\n+static void show_usage(const char *cmd)\n+{\n+ fprintf(stderr, \"Usage: %s [options]\\n\"\n+ \"-l, --loops <num>\\t\\t Number of syscall loops, default 10000000\\n\", cmd);\n+}\n+\n+int main(int argc, char *argv[])\n+{\n+ int i;\n+ int c;\n+ struct option long_options[] = {\n+ {\"loops\", required_argument, 0, 'l'},\n+ {0, 0, 0, 0}};\n+ int option_index = 0;\n+\n+ while ((c = getopt_long(argc, argv, \"l:\", long_options, &option_index)) != -1) {\n+ switch (c) {\n+ case 'l':\n+ loops = atoi(optarg);\n+ if (loops <= 0) {\n+ show_usage(argv[0]);\n+ exit(1);\n+ }\n+ break;\n+ default:\n+ show_usage(argv[0]);\n+ exit(1);\n+ }\n+ }\n+\n+ for (i = 0; i < loops; i++)\n+ syscall(SYS_getpid);\n+\n+ printf(\"# Executed %'d getpid() calls\\n\", loops);\n+ return 0;\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/base/BUILD", "new_path": "test/benchmarks/base/BUILD", "diff": "@@ -48,3 +48,14 @@ benchmark_test(\n\"//test/benchmarks/tools\",\n],\n)\n+\n+benchmark_test(\n+ name = \"syscallbench_test\",\n+ srcs = [\"syscallbench_test.go\"],\n+ visibility = [\"//:sandbox\"],\n+ deps = [\n+ \"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/harness\",\n+ \"//test/benchmarks/tools\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/benchmarks/base/syscallbench_test.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package syscallbench_test\n+\n+import (\n+ \"context\"\n+ \"fmt\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/test/dockerutil\"\n+ \"gvisor.dev/gvisor/test/benchmarks/harness\"\n+ \"gvisor.dev/gvisor/test/benchmarks/tools\"\n+)\n+\n+// BenchmarSyscallbench runs syscallbench on the runtime.\n+func BenchmarkSyscallbench(b *testing.B) {\n+ machine, err := harness.GetMachine()\n+ if err != nil {\n+ b.Fatalf(\"failed to get machine: %v\", err)\n+ }\n+ defer machine.CleanUp()\n+\n+ param := tools.Parameter{\n+ Name: \"syscall\",\n+ Value: \"getpid\",\n+ }\n+ name, err := tools.ParametersToName(param)\n+ if err != nil {\n+ b.Fatalf(\"Failed to parse params: %v\", err)\n+ }\n+ b.Run(name, func(b *testing.B) {\n+ ctx := context.Background()\n+ container := machine.GetContainer(ctx, b)\n+ defer container.CleanUp(ctx)\n+\n+ if err := container.Spawn(\n+ ctx, dockerutil.RunOpts{\n+ Image: \"benchmarks/syscallbench\",\n+ },\n+ \"sleep\", \"24h\",\n+ ); err != nil {\n+ b.Fatalf(\"run failed with: %v\", err)\n+ }\n+\n+ cmd := []string{\"syscallbench\", fmt.Sprintf(\"--loops=%d\", b.N)}\n+ b.ResetTimer()\n+ out, err := container.Exec(ctx, dockerutil.ExecOpts{}, cmd...)\n+ if err != nil {\n+ b.Fatalf(\"failed to run syscallbench: %v, logs:%s\", err, out)\n+ }\n+ })\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
benchmarks: add syscallbench benchmark for syscall performance Signed-off-by: Chen Hui <cedriccchen@tencent.com>
259,858
22.09.2022 10:59:13
25,200
4bb25e196d6982f057d06edddedaf71b298ac5b0
Unmap (prev.End, next.Start) during pma invalidation. This should allow lower-layers to clean-up intermediate structures more effectively, without additional heavy-lifting.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/pma.go", "new_path": "pkg/sentry/mm/pma.go", "diff": "@@ -626,7 +626,27 @@ func (mm *MemoryManager) invalidateLocked(ar hostarch.AddrRange, invalidatePriva\n// Unmap all of ar, not just pseg.Range(), to minimize host\n// syscalls. AddressSpace mappings must be removed before\n// mm.decPrivateRef().\n- mm.unmapASLocked(ar)\n+ //\n+ // Note that we do more than just ar here, and extrapolate\n+ // to the end of any previous region that we may have mapped.\n+ // This is done to ensure that lower layers can fully invalidate\n+ // intermediate pagetable pages during the unmap.\n+ var unmapAR hostarch.AddrRange\n+ if prev := pseg.PrevSegment(); prev.Ok() {\n+ unmapAR.Start = prev.End()\n+ } else {\n+ unmapAR.Start = mm.layout.MinAddr\n+ }\n+ if last := mm.pmas.LowerBoundSegment(ar.End); last.Ok() {\n+ if last.Start() < ar.End {\n+ unmapAR.End = ar.End\n+ } else {\n+ unmapAR.End = last.Start()\n+ }\n+ } else {\n+ unmapAR.End = mm.layout.MaxAddr\n+ }\n+ mm.unmapASLocked(unmapAR)\ndidUnmapAS = true\n}\nif pma.private {\n" } ]
Go
Apache License 2.0
google/gvisor
Unmap (prev.End, next.Start) during pma invalidation. This should allow lower-layers to clean-up intermediate structures more effectively, without additional heavy-lifting. PiperOrigin-RevId: 476144809
259,868
22.09.2022 18:53:30
25,200
c895fa244150ab549d67b1d96eb4eb78e322b6f3
Update `machine.mapPhysical`'s docstring for `panic` -> `throw`.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine.go", "new_path": "pkg/sentry/platform/kvm/machine.go", "diff": "@@ -372,7 +372,7 @@ func (m *machine) hasSlot(physical uintptr) bool {\n// mapPhysical checks for the mapping of a physical range, and installs one if\n// not available. This attempts to be efficient for calls in the hot path.\n//\n-// This panics on error.\n+// This throws on error.\n//\n//go:nosplit\nfunc (m *machine) mapPhysical(physical, length uintptr, phyRegions []physicalRegion) {\n" } ]
Go
Apache License 2.0
google/gvisor
Update `machine.mapPhysical`'s docstring for `panic` -> `throw`. PiperOrigin-RevId: 476249730
259,939
14.09.2022 10:21:28
-28,800
b63b4d6f366e06b15986ee31cd8c3c329ecdf4c1
benchmarks: add hackbench benchmark for scheduler performance
[ { "change_type": "ADD", "old_path": null, "new_path": "images/benchmarks/hackbench/Dockerfile", "diff": "+FROM ubuntu:18.04\n+\n+RUN set -x \\\n+ && apt-get update \\\n+ && apt-get install -y rt-tests \\\n+ && rm -rf /var/lib/apt/lists/*\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/base/BUILD", "new_path": "test/benchmarks/base/BUILD", "diff": "@@ -59,3 +59,14 @@ benchmark_test(\n\"//test/benchmarks/tools\",\n],\n)\n+\n+benchmark_test(\n+ name = \"hackbench_test\",\n+ srcs = [\"hackbench_test.go\"],\n+ visibility = [\"//:sandbox\"],\n+ deps = [\n+ \"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/harness\",\n+ \"//test/benchmarks/tools\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/benchmarks/base/hackbench_test.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package hackbench_test\n+\n+import (\n+ \"context\"\n+ \"os\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/test/dockerutil\"\n+ \"gvisor.dev/gvisor/test/benchmarks/harness\"\n+ \"gvisor.dev/gvisor/test/benchmarks/tools\"\n+)\n+\n+// BenchmarHackbench runs hackbench on the runtime.\n+func BenchmarkHackbench(b *testing.B) {\n+ testCases := []tools.Hackbench{\n+ {\n+ IpcMode: \"pipe\",\n+ ProcessMode: \"thread\",\n+ },\n+ {\n+ IpcMode: \"socket\",\n+ ProcessMode: \"process\",\n+ },\n+ }\n+\n+ machine, err := harness.GetMachine()\n+ if err != nil {\n+ b.Fatalf(\"failed to get machine: %v\", err)\n+ }\n+ defer machine.CleanUp()\n+\n+ for _, tc := range testCases {\n+ ipcMode := tools.Parameter{\n+ Name: \"ipcMode\",\n+ Value: tc.IpcMode,\n+ }\n+ processMode := tools.Parameter{\n+ Name: \"processMode\",\n+ Value: tc.ProcessMode,\n+ }\n+ name, err := tools.ParametersToName(ipcMode, processMode)\n+ if err != nil {\n+ b.Fatalf(\"Failed to parse params: %v\", err)\n+ }\n+ b.Run(name, func(b *testing.B) {\n+ ctx := context.Background()\n+ container := machine.GetContainer(ctx, b)\n+ defer container.CleanUp(ctx)\n+\n+ if err := container.Spawn(\n+ ctx, dockerutil.RunOpts{\n+ Image: \"benchmarks/hackbench\",\n+ },\n+ \"sleep\", \"24h\",\n+ ); err != nil {\n+ b.Fatalf(\"run failed with: %v\", err)\n+ }\n+\n+ cmd := tc.MakeCmd(b)\n+ b.ResetTimer()\n+ out, err := container.Exec(ctx, dockerutil.ExecOpts{}, cmd...)\n+ if err != nil {\n+ b.Fatalf(\"failed to run hackbench: %v, logs:%s\", err, out)\n+ }\n+ tc.Report(b, out)\n+ })\n+ }\n+}\n+\n+// TestMain is the main method for this package.\n+func TestMain(m *testing.M) {\n+ harness.Init()\n+ harness.SetFixedBenchmarks()\n+ os.Exit(m.Run())\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/tools/BUILD", "new_path": "test/benchmarks/tools/BUILD", "diff": "@@ -14,6 +14,7 @@ go_library(\n\"parser_util.go\",\n\"redis.go\",\n\"sysbench.go\",\n+ \"hackbench.go\",\n\"tools.go\",\n],\nvisibility = [\"//:sandbox\"],\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/benchmarks/tools/hackbench.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package tools\n+\n+import (\n+ \"fmt\"\n+ \"regexp\"\n+ \"strconv\"\n+ \"testing\"\n+)\n+\n+// Hackbench makes 'hackbench' commands and parses their output.\n+type Hackbench struct {\n+ IpcMode string // ipc mode: pipe, socket(default)\n+ ProcessMode string // process mode: thread, process(default)\n+}\n+\n+// MakeCmd makes commands for Hackbench.\n+func (s *Hackbench) MakeCmd(b *testing.B) []string {\n+ cmd := []string{\"hackbench\"}\n+ // ipc mode\n+ if s.IpcMode == \"pipe\" {\n+ cmd = append(cmd, \"--pipe\")\n+ }\n+ // group num\n+ cmd = append(cmd, \"--groups=10\")\n+ // process mode\n+ if s.ProcessMode == \"thread\" {\n+ cmd = append(cmd, \"--threads\")\n+ } else {\n+ cmd = append(cmd, \"--process\")\n+ }\n+ // loops\n+ cmd = append(cmd, \"--loops=1000\")\n+ return cmd\n+}\n+\n+// Report reports the relevant metrics for Hackbench.\n+func (s *Hackbench) Report(b *testing.B, output string) {\n+ b.Helper()\n+ result, err := s.parseResult(output)\n+ if err != nil {\n+ b.Fatalf(\"parsing result from %s failed: %v\", output, err)\n+ }\n+ ReportCustomMetric(b, result, \"execution_time\" /*metric name*/, \"s\" /*unit*/)\n+}\n+\n+var hackbenchRegexp = regexp.MustCompile(`Time:\\s*(\\d*.?\\d*)\\n`)\n+\n+func (s *Hackbench) parseResult(data string) (float64, error) {\n+ match := hackbenchRegexp.FindStringSubmatch(data)\n+ if len(match) < 2 {\n+ return 0.0, fmt.Errorf(\"could not find Time: %s\", data)\n+ }\n+ return strconv.ParseFloat(match[1], 64)\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
benchmarks: add hackbench benchmark for scheduler performance Signed-off-by: Chen Hui <cedriccchen@tencent.com>
259,939
14.09.2022 10:44:22
-28,800
ac982d4a93871b69f0089c176e36d4a7413585a8
benchmarks: add more threads arguments for sysbench benchmark
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/base/sysbench_test.go", "new_path": "test/benchmarks/base/sysbench_test.go", "diff": "@@ -16,6 +16,7 @@ package sysbench_test\nimport (\n\"context\"\n+ \"fmt\"\n\"testing\"\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n@@ -25,6 +26,7 @@ import (\ntype testCase struct {\nname string\n+ threads int\ntest tools.Sysbench\n}\n@@ -39,6 +41,15 @@ func BenchmarkSysbench(b *testing.B) {\n},\n},\n},\n+ {\n+ name: \"CPU\",\n+ threads: 16,\n+ test: &tools.SysbenchCPU{\n+ SysbenchBase: tools.SysbenchBase{\n+ Threads: 16,\n+ },\n+ },\n+ },\n{\nname: \"Memory\",\ntest: &tools.SysbenchMemory{\n@@ -47,6 +58,15 @@ func BenchmarkSysbench(b *testing.B) {\n},\n},\n},\n+ {\n+ name: \"Memory\",\n+ threads: 16,\n+ test: &tools.SysbenchMemory{\n+ SysbenchBase: tools.SysbenchBase{\n+ Threads: 16,\n+ },\n+ },\n+ },\n{\nname: \"Mutex\",\ntest: &tools.SysbenchMutex{\n@@ -68,10 +88,22 @@ func BenchmarkSysbench(b *testing.B) {\nName: \"testname\",\nValue: tc.name,\n}\n- name, err := tools.ParametersToName(param)\n+ var name string\n+ if tc.threads != 0 {\n+ threads := tools.Parameter{\n+ Name: \"threads\",\n+ Value: fmt.Sprintf(\"%d\", tc.threads),\n+ }\n+ name, err = tools.ParametersToName(param, threads)\nif err != nil {\nb.Fatalf(\"Failed to parse params: %v\", err)\n}\n+ } else {\n+ name, err = tools.ParametersToName(param)\n+ if err != nil {\n+ b.Fatalf(\"Failed to parse params: %v\", err)\n+ }\n+ }\nb.Run(name, func(b *testing.B) {\nctx := context.Background()\nsysbench := machine.GetContainer(ctx, b)\n" } ]
Go
Apache License 2.0
google/gvisor
benchmarks: add more threads arguments for sysbench benchmark Signed-off-by: Chen Hui <cedriccchen@tencent.com>