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,858 | 27.07.2020 15:34:25 | 25,200 | 4b336f16b8fc85807cc852494ef1e105361135c6 | Enable RBE for standard-tests. | [
{
"change_type": "MODIFY",
"old_path": ".bazelrc",
"new_path": ".bazelrc",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+# RBE requires a strong hash function, such as SHA256.\n+startup --host_jvm_args=-Dbazel.DigestFunction=SHA256\n+\n# Build with C++17.\nbuild --cxxopt=-std=c++17\n@@ -22,11 +25,17 @@ build --stamp --workspace_status_command tools/workspace_status.sh\nbuild:remote --remote_executor=grpcs://remotebuildexecution.googleapis.com\nbuild:remote --project_id=gvisor-rbe\nbuild:remote --remote_instance_name=projects/gvisor-rbe/instances/default_instance\n+build:remote3 --remote_executor=grpcs://remotebuildexecution.googleapis.com\n+build:remote3 --project_id=gvisor-rbe\n+build:remote3 --remote_instance_name=projects/gvisor-rbe/instances/default_instance\n+\n# Enable authentication. This will pick up application default credentials by\n# default. You can use --google_credentials=some_file.json to use a service\n# account credential instead.\nbuild:remote --google_default_credentials=true\nbuild:remote --auth_scope=\"https://www.googleapis.com/auth/cloud-source-tools\"\n+build:remote3 --google_default_credentials=true\n+build:remote3 --auth_scope=\"https://www.googleapis.com/auth/cloud-source-tools\"\n# Add a custom platform and toolchain that builds in a privileged docker\n# container, which is required by our syscall tests.\n@@ -37,8 +46,13 @@ build:remote --platforms=//tools/bazeldefs:rbe_ubuntu1604\nbuild:remote --crosstool_top=@rbe_default//cc:toolchain\nbuild:remote --jobs=50\nbuild:remote --remote_timeout=3600\n-# RBE requires a strong hash function, such as SHA256.\n-startup --host_jvm_args=-Dbazel.DigestFunction=SHA256\n+build:remote3 --host_platform=//tools/bazeldefs:rbe_ubuntu1604_bazel3\n+build:remote3 --extra_toolchains=//tools/bazeldefs:cc-toolchain-clang-x86_64-default_bazel3\n+build:remote3 --extra_execution_platforms=//tools/bazeldefs:rbe_ubuntu1604_bazel3\n+build:remote3 --platforms=//tools/bazeldefs:rbe_ubuntu1604_bazel3\n+build:remote3 --crosstool_top=@rbe_default//cc:toolchain\n+build:remote3 --jobs=50\n+build:remote3 --remote_timeout=3600\n# Set flags for uploading to BES in order to view results in the Bazel Build\n# Results UI.\n"
},
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -42,6 +42,28 @@ http_archive(\n],\n)\n+http_archive(\n+ name = \"io_bazel_rules_go_bazel3\", # To replace the above.\n+ patch_args = [\"-p1\"],\n+ patches = [\n+ \"//tools/nogo:io_bazel_rules_go-visibility.patch\",\n+ ],\n+ sha256 = \"87f0fb9747854cb76a0a82430adccb6269f7d394237104a4523b51061c469171\",\n+ urls = [\n+ \"https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.23.1/rules_go-v0.23.1.tar.gz\",\n+ \"https://github.com/bazelbuild/rules_go/releases/download/v0.23.1/rules_go-v0.23.1.tar.gz\",\n+ ],\n+)\n+\n+http_archive(\n+ name = \"bazel_gazelle_bazel3\", # To replace the above.\n+ sha256 = \"bfd86b3cbe855d6c16c6fce60d76bd51f5c8dbc9cfcaef7a2bb5c1aafd0710e8\",\n+ urls = [\n+ \"https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.21.0/bazel-gazelle-v0.21.0.tar.gz\",\n+ \"https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.21.0/bazel-gazelle-v0.21.0.tar.gz\",\n+ ],\n+)\n+\nload(\"@io_bazel_rules_go//go:deps.bzl\", \"go_register_toolchains\", \"go_rules_dependencies\")\ngo_rules_dependencies()\n@@ -123,6 +145,16 @@ http_archive(\n],\n)\n+http_archive(\n+ name = \"bazel_toolchains_bazel3\", # To replace the above.\n+ sha256 = \"144290c4166bd67e76a54f96cd504ed86416ca3ca82030282760f0823c10be48\",\n+ strip_prefix = \"bazel-toolchains-3.1.1\",\n+ urls = [\n+ \"https://github.com/bazelbuild/bazel-toolchains/releases/download/3.1.1/bazel-toolchains-3.1.1.tar.gz\",\n+ \"https://mirror.bazel.build/github.com/bazelbuild/bazel-toolchains/releases/download/3.1.1/bazel-toolchains-3.1.1.tar.gz\",\n+ ],\n+)\n+\n# Creates a default toolchain config for RBE.\nload(\"@bazel_toolchains//rules:rbe_repo.bzl\", \"rbe_autoconfig\")\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazel.mk",
"new_path": "tools/bazel.mk",
"diff": "@@ -74,6 +74,11 @@ FULL_DOCKER_RUN_OPTIONS += --group-add $(KVM_GROUP)\nendif\nendif\n+# Load the appropriate config.\n+ifneq (,$(BAZEL_CONFIG))\n+OPTIONS += --config=$(BAZEL_CONFIG)\n+endif\n+\nbazel-image: load-default\n@if docker ps --all | grep $(BUILDER_NAME); then docker rm -f $(BUILDER_NAME); fi\ndocker run --user 0:0 --entrypoint \"\" --name $(BUILDER_NAME) \\\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazeldefs/BUILD",
"new_path": "tools/bazeldefs/BUILD",
"diff": "@@ -49,3 +49,40 @@ rbe_toolchain(\ntoolchain = \"@bazel_toolchains//configs/ubuntu16_04_clang/10.0.0/bazel_2.0.0/cc:cc-compiler-k8\",\ntoolchain_type = \"@bazel_tools//tools/cpp:toolchain_type\",\n)\n+\n+# Updated versions of the above, compatible with bazel3.\n+rbe_platform(\n+ name = \"rbe_ubuntu1604_bazel3\",\n+ constraint_values = [\n+ \"@bazel_tools//platforms:x86_64\",\n+ \"@bazel_tools//platforms:linux\",\n+ \"@bazel_tools//tools/cpp:clang\",\n+ \"@bazel_toolchains_bazel3//constraints:xenial\",\n+ \"@bazel_toolchains_bazel3//constraints/sanitizers:support_msan\",\n+ ],\n+ remote_execution_properties = \"\"\"\n+ properties: {\n+ name: \"container-image\"\n+ value:\"docker://gcr.io/cloud-marketplace/google/rbe-ubuntu16-04@sha256:b516a2d69537cb40a7c6a7d92d0008abb29fba8725243772bdaf2c83f1be2272\"\n+ }\n+ properties: {\n+ name: \"dockerAddCapabilities\"\n+ value: \"SYS_ADMIN\"\n+ }\n+ properties: {\n+ name: \"dockerPrivileged\"\n+ value: \"true\"\n+ }\n+ \"\"\",\n+)\n+\n+rbe_toolchain(\n+ name = \"cc-toolchain-clang-x86_64-default_bazel3\",\n+ exec_compatible_with = [],\n+ tags = [\n+ \"manual\",\n+ ],\n+ target_compatible_with = [],\n+ toolchain = \"@bazel_toolchains_bazel3//configs/ubuntu16_04_clang/11.0.0/bazel_3.1.0/cc:cc-compiler-k8\",\n+ toolchain_type = \"@bazel_tools//tools/cpp:toolchain_type\",\n+)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable RBE for standard-tests.
PiperOrigin-RevId: 323454998 |
259,885 | 27.07.2020 19:25:31 | 25,200 | 18c246359663ae7e424f94225f11f87cc63eccd9 | Fix strace for epoll event arrays. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/epoll.go",
"new_path": "pkg/sentry/strace/epoll.go",
"diff": "@@ -50,10 +50,10 @@ func epollEvents(t *kernel.Task, eventsAddr usermem.Addr, numEvents, maxBytes ui\nsb.WriteString(\"...\")\nbreak\n}\n- if _, ok := addr.AddLength(uint64(linux.SizeOfEpollEvent)); !ok {\n- fmt.Fprintf(&sb, \"{error reading event at %#x: EFAULT}\", addr)\n- continue\n- }\n+ // Allowing addr to overflow is consistent with Linux, and harmless; if\n+ // this isn't the last iteration of the loop, the next call to CopyIn\n+ // will just fail with EFAULT.\n+ addr, _ = addr.AddLength(uint64(linux.SizeOfEpollEvent))\n}\nsb.WriteString(\"}\")\nreturn sb.String()\n@@ -75,7 +75,7 @@ var epollEventEvents = abi.FlagSet{\n{Flag: linux.EPOLLPRI, Name: \"EPOLLPRI\"},\n{Flag: linux.EPOLLOUT, Name: \"EPOLLOUT\"},\n{Flag: linux.EPOLLERR, Name: \"EPOLLERR\"},\n- {Flag: linux.EPOLLHUP, Name: \"EPULLHUP\"},\n+ {Flag: linux.EPOLLHUP, Name: \"EPOLLHUP\"},\n{Flag: linux.EPOLLRDNORM, Name: \"EPOLLRDNORM\"},\n{Flag: linux.EPOLLRDBAND, Name: \"EPOLLRDBAND\"},\n{Flag: linux.EPOLLWRNORM, Name: \"EPOLLWRNORM\"},\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix strace for epoll event arrays.
PiperOrigin-RevId: 323491461 |
259,858 | 28.07.2020 09:39:08 | 25,200 | a05ea20ef1107cc0a4ace94d6dffd7c7e590b264 | Don't attempt to use the secret if it does not exist.
Fixes | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/go.yml",
"new_path": ".github/workflows/go.yml",
"diff": "@@ -11,7 +11,13 @@ jobs:\ngenerate:\nruns-on: ubuntu-latest\nsteps:\n- - run: |\n+ - id: setup\n+ run: |\n+ if ! [[ -z \"${{ secrets.GO_TOKEN }}\" ]]; then\n+ echo ::set-output has_token=true\n+ else\n+ echo ::set-output has_token=false\n+ fi\njq -nc '{\"state\": \"pending\", \"context\": \"go tests\"}' | \\\ncurl -sL -X POST -d @- \\\n-H \"Content-Type: application/json\" \\\n@@ -19,12 +25,12 @@ jobs:\n\"${{ github.event.pull_request.statuses_url }}\"\nif: github.event_name == 'pull_request'\n- uses: actions/checkout@v2\n- if: github.event_name == 'push'\n+ if: github.event_name == 'push' && steps.setup.outputs.has_token == 'true'\nwith:\nfetch-depth: 0\ntoken: '${{ secrets.GO_TOKEN }}'\n- uses: actions/checkout@v2\n- if: github.event_name == 'pull_request'\n+ if: github.event_name == 'pull_request' || steps.setup.outputs.has_token != 'true'\nwith:\nfetch-depth: 0\n- uses: actions/setup-go@v2\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't attempt to use the secret if it does not exist.
Fixes #3326
PiperOrigin-RevId: 323589669 |
259,975 | 28.07.2020 12:51:54 | 25,200 | 5873b0f43f5ff4d811f951baaacb7bbe8b1a486c | Port tensorflow benchmark. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/tensorflow/Dockerfile",
"diff": "+FROM tensorflow/tensorflow:1.13.2\n+\n+RUN apt-get update \\\n+ && apt-get install -y git\n+RUN git clone --depth 1 https://github.com/aymericdamien/TensorFlow-Examples.git\n+RUN python -m pip install -U pip setuptools\n+RUN python -m pip install matplotlib\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/media/ffmpeg_test.go",
"new_path": "test/benchmarks/media/ffmpeg_test.go",
"diff": "@@ -33,6 +33,7 @@ func BenchmarkFfmpeg(b *testing.B) {\nctx := context.Background()\ncontainer := machine.GetContainer(ctx, b)\n+ defer container.CleanUp(ctx)\ncmd := strings.Split(\"ffmpeg -i video.mp4 -c:v libx264 -preset veryslow output.mp4\", \" \")\nb.ResetTimer()\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/benchmarks/ml/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"ml\",\n+ testonly = 1,\n+ srcs = [\"ml.go\"],\n+ deps = [\"//test/benchmarks/harness\"],\n+)\n+\n+go_test(\n+ name = \"ml_test\",\n+ size = \"large\",\n+ srcs = [\"tensorflow_test.go\"],\n+ library = \":ml\",\n+ deps = [\n+ \"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/harness\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/benchmarks/ml/ml.go",
"diff": "+// Copyright 2020 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 ml holds benchmarks around machine learning performance.\n+package ml\n+\n+import (\n+ \"os\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/test/benchmarks/harness\"\n+)\n+\n+var h harness.Harness\n+\n+// TestMain is the main method for package ml.\n+func TestMain(m *testing.M) {\n+ h.Init()\n+ os.Exit(m.Run())\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/benchmarks/ml/tensorflow_test.go",
"diff": "+// Copyright 2020 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+package ml\n+\n+import (\n+ \"context\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/test/dockerutil\"\n+ \"gvisor.dev/gvisor/test/benchmarks/harness\"\n+)\n+\n+// BenchmarkTensorflow runs workloads from a TensorFlow tutorial.\n+// See: https://github.com/aymericdamien/TensorFlow-Examples\n+func BenchmarkTensorflow(b *testing.B) {\n+ workloads := map[string]string{\n+ \"GradientDecisionTree\": \"2_BasicModels/gradient_boosted_decision_tree.py\",\n+ \"Kmeans\": \"2_BasicModels/kmeans.py\",\n+ \"LogisticRegression\": \"2_BasicModels/logistic_regression.py\",\n+ \"NearestNeighbor\": \"2_BasicModels/nearest_neighbor.py\",\n+ \"RandomForest\": \"2_BasicModels/random_forest.py\",\n+ \"ConvolutionalNetwork\": \"3_NeuralNetworks/convolutional_network.py\",\n+ \"MultilayerPerceptron\": \"3_NeuralNetworks/multilayer_perceptron.py\",\n+ \"NeuralNetwork\": \"3_NeuralNetworks/neural_network.py\",\n+ }\n+\n+ machine, err := h.GetMachine()\n+ if err != nil {\n+ b.Fatalf(\"failed to get machine: %v\", err)\n+ }\n+ defer machine.CleanUp()\n+\n+ for name, workload := range workloads {\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+ b.ResetTimer()\n+ for i := 0; i < b.N; i++ {\n+ b.StopTimer()\n+ if err := harness.DropCaches(machine); err != nil {\n+ b.Skipf(\"failed to drop caches: %v. You probably need root.\", err)\n+ }\n+ b.StartTimer()\n+\n+ if out, err := container.Run(ctx, dockerutil.RunOpts{\n+ Image: \"benchmarks/tensorflow\",\n+ Env: []string{\"PYTHONPATH=$PYTHONPATH:/TensorFlow-Examples/examples\"},\n+ WorkDir: \"/TensorFlow-Examples/examples\",\n+ }, \"python\", workload); err != nil {\n+ b.Fatalf(\"failed to run container: %v logs: %s\", err, out)\n+ }\n+ }\n+ })\n+ }\n+\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Port tensorflow benchmark.
PiperOrigin-RevId: 323633737 |
259,858 | 28.07.2020 13:51:38 | 25,200 | 7881610a3f9ac7382221ee17da908ff8f86053b5 | Use the appropriate remote configuration. | [
{
"change_type": "MODIFY",
"old_path": ".bazelrc",
"new_path": ".bazelrc",
"diff": "@@ -23,10 +23,16 @@ build --stamp --workspace_status_command tools/workspace_status.sh\n# Enable remote execution so actions are performed on the remote systems.\nbuild:remote --remote_executor=grpcs://remotebuildexecution.googleapis.com\n+build:remote --bes_backend=buildeventservice.googleapis.com\n+build:remote --bes_results_url=\"https://source.cloud.google.com/results/invocations\"\n+build:remote --bes_timeout=600s\nbuild:remote --project_id=gvisor-rbe\nbuild:remote --remote_instance_name=projects/gvisor-rbe/instances/default_instance\nbuild:remote3 --remote_executor=grpcs://remotebuildexecution.googleapis.com\nbuild:remote3 --project_id=gvisor-rbe\n+build:remote3 --bes_backend=buildeventservice.googleapis.com\n+build:remote3 --bes_results_url=\"https://source.cloud.google.com/results/invocations\"\n+build:remote3 --bes_timeout=600s\nbuild:remote3 --remote_instance_name=projects/gvisor-rbe/instances/default_instance\n# Enable authentication. This will pick up application default credentials by\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/common_build.sh",
"new_path": "scripts/common_build.sh",
"diff": "@@ -31,9 +31,9 @@ declare -a BAZEL_FLAGS=(\n\"--keep_going\"\n\"--verbose_failures=true\"\n)\n-if [[ -v KOKORO_BAZEL_AUTH_CREDENTIAL ]]; then\n+# If running via kokoro, use the remote config.\n+if [[ -v KOKORO_ARTIFACTS_DIR ]]; then\nBAZEL_FLAGS+=(\n- \"--auth_credentials=${KOKORO_BAZEL_AUTH_CREDENTIAL}\"\n\"--config=remote\"\n)\nfi\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use the appropriate remote configuration.
PiperOrigin-RevId: 323646156 |
259,858 | 28.07.2020 16:04:34 | 25,200 | eca2fcce94de90a652b7924ef1ce971a9e0fe327 | Add MIT license to top-level LICENSE file.
This is needed for e.g. pkg/safecopy/memcpy_amd64.s. | [
{
"change_type": "MODIFY",
"old_path": "LICENSE",
"new_path": "LICENSE",
"diff": "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n+\n+------------------\n+\n+Some files carry the following license, noted at the top of each file:\n+\n+ Permission is hereby granted, free of charge, to any person obtaining a copy\n+ of this software and associated documentation files (the \"Software\"), to deal\n+ in the Software without restriction, including without limitation the rights\n+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ copies of the Software, and to permit persons to whom the Software is\n+ furnished to do so, subject to the following conditions:\n+\n+ The above copyright notice and this permission notice shall be included in\n+ all copies or substantial portions of the Software.\n+\n+ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ THE SOFTWARE.\n\\ No newline at end of file\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add MIT license to top-level LICENSE file.
This is needed for e.g. pkg/safecopy/memcpy_amd64.s.
PiperOrigin-RevId: 323673052 |
259,858 | 28.07.2020 16:21:41 | 25,200 | c1c643abe7be45991c8004d0de2b31716702d527 | Delete unused script. | [
{
"change_type": "DELETE",
"old_path": "scripts/issue_reviver.sh",
"new_path": null,
"diff": "-#!/bin/bash\n-\n-# Copyright 2019 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-DIR=$(dirname $0)\n-source \"${DIR}\"/common.sh\n-\n-# Provide a credential file if available.\n-export OAUTH_TOKEN_FILE=\"\"\n-if [[ -v KOKORO_GITHUB_ACCESS_TOKEN ]]; then\n- OAUTH_TOKEN_FILE=\"${KOKORO_KEYSTORE_DIR}/${KOKORO_GITHUB_ACCESS_TOKEN}\"\n-fi\n-\n-REPO_ROOT=$(cd \"$(dirname \"${DIR}\")\"; pwd)\n-run //tools/issue_reviver:issue_reviver --path \"${REPO_ROOT}\" --oauth-token-file=\"${OAUTH_TOKEN_FILE}\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Delete unused script.
PiperOrigin-RevId: 323676189 |
259,992 | 28.07.2020 21:22:52 | 25,200 | f82dd8ddb477b8923d1db12654a62d55d613019c | Redirect TODO to GitHub issues | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -423,7 +423,7 @@ func AddressAndFamily(addr []byte) (tcpip.FullAddress, uint16, *syserr.Error) {\nreturn tcpip.FullAddress{}, family, syserr.ErrInvalidArgument\n}\n- // TODO(b/129292371): Return protocol too.\n+ // TODO(gvisor.dev/issue/173): Return protocol too.\nreturn tcpip.FullAddress{\nNIC: tcpip.NICID(a.InterfaceIndex),\nAddr: tcpip.Address(a.HardwareAddr[:header.EthernetAddressSize]),\n@@ -2418,7 +2418,7 @@ func ConvertAddress(family int, addr tcpip.FullAddress) (linux.SockAddr, uint32)\nreturn &out, uint32(sockAddrInet6Size)\ncase linux.AF_PACKET:\n- // TODO(b/129292371): Return protocol too.\n+ // TODO(gvisor.dev/issue/173): Return protocol too.\nvar out linux.SockAddrLink\nout.Family = linux.AF_PACKET\nout.InterfaceIndex = int32(addr.NIC)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -181,7 +181,7 @@ func (n *NIC) disableLocked() *tcpip.Error {\nreturn nil\n}\n- // TODO(b/147015577): Should Routes that are currently bound to n be\n+ // TODO(gvisor.dev/issue/1491): Should Routes that are currently bound to n be\n// invalidated? Currently, Routes will continue to work when a NIC is enabled\n// again, and applications may not know that the underlying NIC was ever\n// disabled.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -867,9 +867,9 @@ func TestRouteWithDownNIC(t *testing.T) {\n// Writes with Routes that use NIC1 after being brought up should\n// succeed.\n//\n- // TODO(b/147015577): Should we instead completely invalidate all\n- // Routes that were bound to a NIC that was brought down at some\n- // point?\n+ // TODO(gvisor.dev/issue/1491): Should we instead completely\n+ // invalidate all Routes that were bound to a NIC that was brought\n+ // down at some point?\nif err := upFn(s, nicID1); err != nil {\nt.Fatalf(\"test.upFn(_, %d): %s\", nicID1, err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/packet/endpoint.go",
"new_path": "pkg/tcpip/transport/packet/endpoint.go",
"diff": "@@ -193,7 +193,7 @@ func (ep *endpoint) Read(addr *tcpip.FullAddress) (buffer.View, tcpip.ControlMes\n}\nfunc (ep *endpoint) Write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, <-chan struct{}, *tcpip.Error) {\n- // TODO(b/129292371): Implement.\n+ // TODO(gvisor.dev/issue/173): Implement.\nreturn 0, nil, tcpip.ErrInvalidOptionValue\n}\n@@ -432,7 +432,7 @@ func (ep *endpoint) HandlePacket(nicID tcpip.NICID, localAddr tcpip.LinkAddress,\n// Push new packet into receive list and increment the buffer size.\nvar packet packet\n- // TODO(b/129292371): Return network protocol.\n+ // TODO(gvisor.dev/issue/173): Return network protocol.\nif len(pkt.LinkHeader) > 0 {\n// Get info directly from the ethernet header.\nhdr := header.Ethernet(pkt.LinkHeader)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/packet_socket.cc",
"new_path": "test/syscalls/linux/packet_socket.cc",
"diff": "@@ -188,7 +188,7 @@ void ReceiveMessage(int sock, int ifindex) {\n// sizeof(sockaddr_ll).\nASSERT_THAT(src_len, AnyOf(Eq(sizeof(src)), Eq(sizeof(src) - 2)));\n- // TODO(b/129292371): Verify protocol once we return it.\n+ // TODO(gvisor.dev/issue/173): Verify protocol once we return it.\n// Verify the source address.\nEXPECT_EQ(src.sll_family, AF_PACKET);\nEXPECT_EQ(src.sll_ifindex, ifindex);\n@@ -234,7 +234,7 @@ TEST_P(CookedPacketTest, Receive) {\n// Send via a packet socket.\nTEST_P(CookedPacketTest, Send) {\n- // TODO(b/129292371): Remove once we support packet socket writing.\n+ // TODO(gvisor.dev/issue/173): Remove once we support packet socket writing.\nSKIP_IF(IsRunningOnGvisor());\n// Let's send a UDP packet and receive it using a regular UDP socket.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/packet_socket_raw.cc",
"new_path": "test/syscalls/linux/packet_socket_raw.cc",
"diff": "@@ -195,7 +195,7 @@ TEST_P(RawPacketTest, Receive) {\n// sizeof(sockaddr_ll).\nASSERT_THAT(src_len, AnyOf(Eq(sizeof(src)), Eq(sizeof(src) - 2)));\n- // TODO(b/129292371): Verify protocol once we return it.\n+ // TODO(gvisor.dev/issue/173): Verify protocol once we return it.\n// Verify the source address.\nEXPECT_EQ(src.sll_family, AF_PACKET);\nEXPECT_EQ(src.sll_ifindex, GetLoopbackIndex());\n@@ -240,7 +240,7 @@ TEST_P(RawPacketTest, Receive) {\n// Send via a packet socket.\nTEST_P(RawPacketTest, Send) {\n- // TODO(b/129292371): Remove once we support packet socket writing.\n+ // TODO(gvisor.dev/issue/173): Remove once we support packet socket writing.\nSKIP_IF(IsRunningOnGvisor());\n// Let's send a UDP packet and receive it using a regular UDP socket.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Redirect TODO to GitHub issues
PiperOrigin-RevId: 323715260 |
259,975 | 29.07.2020 10:03:57 | 25,200 | 6b4e11ab5074d41044e63337973ac2438ce2278e | Port node benchmark. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/hey/Dockerfile",
"diff": "+FROM ubuntu:18.04\n+\n+RUN set -x \\\n+ && apt-get update \\\n+ && apt-get install -y \\\n+ wget \\\n+ && rm -rf /var/lib/apt/lists/*\n+\n+RUN wget https://storage.googleapis.com/hey-release/hey_linux_amd64 \\\n+ && chmod 777 hey_linux_amd64 \\\n+ && cp hey_linux_amd64 /bin/hey \\\n+ && rm hey_linux_amd64\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/node/Dockerfile",
"diff": "+FROM node:onbuild\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/node/index.hbs",
"diff": "+<!DOCTYPE html>\n+<html>\n+<body>\n+ {{#each text}}\n+ <p>{{this}}</p>\n+ {{/each}}\n+</body>\n+</html>\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/node/index.js",
"diff": "+const app = require('express')();\n+const path = require('path');\n+const redis = require('redis');\n+const srs = require('secure-random-string');\n+\n+// The hostname is the first argument.\n+const host_name = process.argv[2];\n+\n+var client = redis.createClient({host: host_name, detect_buffers: true});\n+\n+app.set('views', __dirname);\n+app.set('view engine', 'hbs');\n+\n+app.get('/', (req, res) => {\n+ var tmp = [];\n+ /* Pull four random keys from the redis server. */\n+ for (i = 0; i < 4; i++) {\n+ client.get(Math.floor(Math.random() * (100)), function(err, reply) {\n+ tmp.push(reply.toString());\n+ });\n+ }\n+ res.render('index', {text: tmp});\n+});\n+\n+/**\n+ * Securely generate a random string.\n+ * @param {number} len\n+ * @return {string}\n+ */\n+function randomBody(len) {\n+ return srs({alphanumeric: true, length: len});\n+}\n+\n+/** Mutates one hundred keys randomly. */\n+function generateText() {\n+ for (i = 0; i < 100; i++) {\n+ client.set(i, randomBody(1024));\n+ }\n+}\n+\n+generateText();\n+app.listen(8080);\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/node/package-lock.json",
"diff": "+{\n+ \"name\": \"nodedum\",\n+ \"version\": \"1.0.0\",\n+ \"lockfileVersion\": 1,\n+ \"requires\": true,\n+ \"dependencies\": {\n+ \"accepts\": {\n+ \"version\": \"1.3.5\",\n+ \"resolved\": \"https://registry.npmjs.org/accepts/-/accepts-1.3.5.tgz\",\n+ \"integrity\": \"sha1-63d99gEXI6OxTopywIBcjoZ0a9I=\",\n+ \"requires\": {\n+ \"mime-types\": \"~2.1.18\",\n+ \"negotiator\": \"0.6.1\"\n+ }\n+ },\n+ \"array-flatten\": {\n+ \"version\": \"1.1.1\",\n+ \"resolved\": \"https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz\",\n+ \"integrity\": \"sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=\"\n+ },\n+ \"async\": {\n+ \"version\": \"2.6.2\",\n+ \"resolved\": \"https://registry.npmjs.org/async/-/async-2.6.2.tgz\",\n+ \"integrity\": \"sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==\",\n+ \"requires\": {\n+ \"lodash\": \"^4.17.11\"\n+ }\n+ },\n+ \"body-parser\": {\n+ \"version\": \"1.18.3\",\n+ \"resolved\": \"https://registry.npmjs.org/body-parser/-/body-parser-1.18.3.tgz\",\n+ \"integrity\": \"sha1-WykhmP/dVTs6DyDe0FkrlWlVyLQ=\",\n+ \"requires\": {\n+ \"bytes\": \"3.0.0\",\n+ \"content-type\": \"~1.0.4\",\n+ \"debug\": \"2.6.9\",\n+ \"depd\": \"~1.1.2\",\n+ \"http-errors\": \"~1.6.3\",\n+ \"iconv-lite\": \"0.4.23\",\n+ \"on-finished\": \"~2.3.0\",\n+ \"qs\": \"6.5.2\",\n+ \"raw-body\": \"2.3.3\",\n+ \"type-is\": \"~1.6.16\"\n+ }\n+ },\n+ \"bytes\": {\n+ \"version\": \"3.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz\",\n+ \"integrity\": \"sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=\"\n+ },\n+ \"commander\": {\n+ \"version\": \"2.20.0\",\n+ \"resolved\": \"https://registry.npmjs.org/commander/-/commander-2.20.0.tgz\",\n+ \"integrity\": \"sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==\",\n+ \"optional\": true\n+ },\n+ \"content-disposition\": {\n+ \"version\": \"0.5.2\",\n+ \"resolved\": \"https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz\",\n+ \"integrity\": \"sha1-DPaLud318r55YcOoUXjLhdunjLQ=\"\n+ },\n+ \"content-type\": {\n+ \"version\": \"1.0.4\",\n+ \"resolved\": \"https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz\",\n+ \"integrity\": \"sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==\"\n+ },\n+ \"cookie\": {\n+ \"version\": \"0.3.1\",\n+ \"resolved\": \"https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz\",\n+ \"integrity\": \"sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=\"\n+ },\n+ \"cookie-signature\": {\n+ \"version\": \"1.0.6\",\n+ \"resolved\": \"https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz\",\n+ \"integrity\": \"sha1-4wOogrNCzD7oylE6eZmXNNqzriw=\"\n+ },\n+ \"debug\": {\n+ \"version\": \"2.6.9\",\n+ \"resolved\": \"https://registry.npmjs.org/debug/-/debug-2.6.9.tgz\",\n+ \"integrity\": \"sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==\",\n+ \"requires\": {\n+ \"ms\": \"2.0.0\"\n+ }\n+ },\n+ \"depd\": {\n+ \"version\": \"1.1.2\",\n+ \"resolved\": \"https://registry.npmjs.org/depd/-/depd-1.1.2.tgz\",\n+ \"integrity\": \"sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=\"\n+ },\n+ \"destroy\": {\n+ \"version\": \"1.0.4\",\n+ \"resolved\": \"https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz\",\n+ \"integrity\": \"sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=\"\n+ },\n+ \"double-ended-queue\": {\n+ \"version\": \"2.1.0-0\",\n+ \"resolved\": \"https://registry.npmjs.org/double-ended-queue/-/double-ended-queue-2.1.0-0.tgz\",\n+ \"integrity\": \"sha1-ED01J/0xUo9AGIEwyEHv3XgmTlw=\"\n+ },\n+ \"ee-first\": {\n+ \"version\": \"1.1.1\",\n+ \"resolved\": \"https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz\",\n+ \"integrity\": \"sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=\"\n+ },\n+ \"encodeurl\": {\n+ \"version\": \"1.0.2\",\n+ \"resolved\": \"https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz\",\n+ \"integrity\": \"sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=\"\n+ },\n+ \"escape-html\": {\n+ \"version\": \"1.0.3\",\n+ \"resolved\": \"https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz\",\n+ \"integrity\": \"sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=\"\n+ },\n+ \"etag\": {\n+ \"version\": \"1.8.1\",\n+ \"resolved\": \"https://registry.npmjs.org/etag/-/etag-1.8.1.tgz\",\n+ \"integrity\": \"sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=\"\n+ },\n+ \"express\": {\n+ \"version\": \"4.16.4\",\n+ \"resolved\": \"https://registry.npmjs.org/express/-/express-4.16.4.tgz\",\n+ \"integrity\": \"sha512-j12Uuyb4FMrd/qQAm6uCHAkPtO8FDTRJZBDd5D2KOL2eLaz1yUNdUB/NOIyq0iU4q4cFarsUCrnFDPBcnksuOg==\",\n+ \"requires\": {\n+ \"accepts\": \"~1.3.5\",\n+ \"array-flatten\": \"1.1.1\",\n+ \"body-parser\": \"1.18.3\",\n+ \"content-disposition\": \"0.5.2\",\n+ \"content-type\": \"~1.0.4\",\n+ \"cookie\": \"0.3.1\",\n+ \"cookie-signature\": \"1.0.6\",\n+ \"debug\": \"2.6.9\",\n+ \"depd\": \"~1.1.2\",\n+ \"encodeurl\": \"~1.0.2\",\n+ \"escape-html\": \"~1.0.3\",\n+ \"etag\": \"~1.8.1\",\n+ \"finalhandler\": \"1.1.1\",\n+ \"fresh\": \"0.5.2\",\n+ \"merge-descriptors\": \"1.0.1\",\n+ \"methods\": \"~1.1.2\",\n+ \"on-finished\": \"~2.3.0\",\n+ \"parseurl\": \"~1.3.2\",\n+ \"path-to-regexp\": \"0.1.7\",\n+ \"proxy-addr\": \"~2.0.4\",\n+ \"qs\": \"6.5.2\",\n+ \"range-parser\": \"~1.2.0\",\n+ \"safe-buffer\": \"5.1.2\",\n+ \"send\": \"0.16.2\",\n+ \"serve-static\": \"1.13.2\",\n+ \"setprototypeof\": \"1.1.0\",\n+ \"statuses\": \"~1.4.0\",\n+ \"type-is\": \"~1.6.16\",\n+ \"utils-merge\": \"1.0.1\",\n+ \"vary\": \"~1.1.2\"\n+ }\n+ },\n+ \"finalhandler\": {\n+ \"version\": \"1.1.1\",\n+ \"resolved\": \"http://registry.npmjs.org/finalhandler/-/finalhandler-1.1.1.tgz\",\n+ \"integrity\": \"sha512-Y1GUDo39ez4aHAw7MysnUD5JzYX+WaIj8I57kO3aEPT1fFRL4sr7mjei97FgnwhAyyzRYmQZaTHb2+9uZ1dPtg==\",\n+ \"requires\": {\n+ \"debug\": \"2.6.9\",\n+ \"encodeurl\": \"~1.0.2\",\n+ \"escape-html\": \"~1.0.3\",\n+ \"on-finished\": \"~2.3.0\",\n+ \"parseurl\": \"~1.3.2\",\n+ \"statuses\": \"~1.4.0\",\n+ \"unpipe\": \"~1.0.0\"\n+ }\n+ },\n+ \"foreachasync\": {\n+ \"version\": \"3.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/foreachasync/-/foreachasync-3.0.0.tgz\",\n+ \"integrity\": \"sha1-VQKYfchxS+M5IJfzLgBxyd7gfPY=\"\n+ },\n+ \"forwarded\": {\n+ \"version\": \"0.1.2\",\n+ \"resolved\": \"https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz\",\n+ \"integrity\": \"sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=\"\n+ },\n+ \"fresh\": {\n+ \"version\": \"0.5.2\",\n+ \"resolved\": \"https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz\",\n+ \"integrity\": \"sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=\"\n+ },\n+ \"handlebars\": {\n+ \"version\": \"4.0.14\",\n+ \"resolved\": \"https://registry.npmjs.org/handlebars/-/handlebars-4.0.14.tgz\",\n+ \"integrity\": \"sha512-E7tDoyAA8ilZIV3xDJgl18sX3M8xB9/fMw8+mfW4msLW8jlX97bAnWgT3pmaNXuvzIEgSBMnAHfuXsB2hdzfow==\",\n+ \"requires\": {\n+ \"async\": \"^2.5.0\",\n+ \"optimist\": \"^0.6.1\",\n+ \"source-map\": \"^0.6.1\",\n+ \"uglify-js\": \"^3.1.4\"\n+ }\n+ },\n+ \"hbs\": {\n+ \"version\": \"4.0.4\",\n+ \"resolved\": \"https://registry.npmjs.org/hbs/-/hbs-4.0.4.tgz\",\n+ \"integrity\": \"sha512-esVlyV/V59mKkwFai5YmPRSNIWZzhqL5YMN0++ueMxyK1cCfPa5f6JiHtapPKAIVAhQR6rpGxow0troav9WMEg==\",\n+ \"requires\": {\n+ \"handlebars\": \"4.0.14\",\n+ \"walk\": \"2.3.9\"\n+ }\n+ },\n+ \"http-errors\": {\n+ \"version\": \"1.6.3\",\n+ \"resolved\": \"http://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz\",\n+ \"integrity\": \"sha1-i1VoC7S+KDoLW/TqLjhYC+HZMg0=\",\n+ \"requires\": {\n+ \"depd\": \"~1.1.2\",\n+ \"inherits\": \"2.0.3\",\n+ \"setprototypeof\": \"1.1.0\",\n+ \"statuses\": \">= 1.4.0 < 2\"\n+ }\n+ },\n+ \"iconv-lite\": {\n+ \"version\": \"0.4.23\",\n+ \"resolved\": \"https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.23.tgz\",\n+ \"integrity\": \"sha512-neyTUVFtahjf0mB3dZT77u+8O0QB89jFdnBkd5P1JgYPbPaia3gXXOVL2fq8VyU2gMMD7SaN7QukTB/pmXYvDA==\",\n+ \"requires\": {\n+ \"safer-buffer\": \">= 2.1.2 < 3\"\n+ }\n+ },\n+ \"inherits\": {\n+ \"version\": \"2.0.3\",\n+ \"resolved\": \"https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz\",\n+ \"integrity\": \"sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=\"\n+ },\n+ \"ipaddr.js\": {\n+ \"version\": \"1.8.0\",\n+ \"resolved\": \"https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.8.0.tgz\",\n+ \"integrity\": \"sha1-6qM9bd16zo9/b+DJygRA5wZzix4=\"\n+ },\n+ \"lodash\": {\n+ \"version\": \"4.17.15\",\n+ \"resolved\": \"https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz\",\n+ \"integrity\": \"sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==\"\n+ },\n+ \"media-typer\": {\n+ \"version\": \"0.3.0\",\n+ \"resolved\": \"http://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz\",\n+ \"integrity\": \"sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=\"\n+ },\n+ \"merge-descriptors\": {\n+ \"version\": \"1.0.1\",\n+ \"resolved\": \"https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz\",\n+ \"integrity\": \"sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=\"\n+ },\n+ \"methods\": {\n+ \"version\": \"1.1.2\",\n+ \"resolved\": \"https://registry.npmjs.org/methods/-/methods-1.1.2.tgz\",\n+ \"integrity\": \"sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=\"\n+ },\n+ \"mime\": {\n+ \"version\": \"1.4.1\",\n+ \"resolved\": \"https://registry.npmjs.org/mime/-/mime-1.4.1.tgz\",\n+ \"integrity\": \"sha512-KI1+qOZu5DcW6wayYHSzR/tXKCDC5Om4s1z2QJjDULzLcmf3DvzS7oluY4HCTrc+9FiKmWUgeNLg7W3uIQvxtQ==\"\n+ },\n+ \"mime-db\": {\n+ \"version\": \"1.37.0\",\n+ \"resolved\": \"https://registry.npmjs.org/mime-db/-/mime-db-1.37.0.tgz\",\n+ \"integrity\": \"sha512-R3C4db6bgQhlIhPU48fUtdVmKnflq+hRdad7IyKhtFj06VPNVdk2RhiYL3UjQIlso8L+YxAtFkobT0VK+S/ybg==\"\n+ },\n+ \"mime-types\": {\n+ \"version\": \"2.1.21\",\n+ \"resolved\": \"https://registry.npmjs.org/mime-types/-/mime-types-2.1.21.tgz\",\n+ \"integrity\": \"sha512-3iL6DbwpyLzjR3xHSFNFeb9Nz/M8WDkX33t1GFQnFOllWk8pOrh/LSrB5OXlnlW5P9LH73X6loW/eogc+F5lJg==\",\n+ \"requires\": {\n+ \"mime-db\": \"~1.37.0\"\n+ }\n+ },\n+ \"minimist\": {\n+ \"version\": \"0.0.10\",\n+ \"resolved\": \"https://registry.npmjs.org/minimist/-/minimist-0.0.10.tgz\",\n+ \"integrity\": \"sha1-3j+YVD2/lggr5IrRoMfNqDYwHc8=\"\n+ },\n+ \"ms\": {\n+ \"version\": \"2.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/ms/-/ms-2.0.0.tgz\",\n+ \"integrity\": \"sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=\"\n+ },\n+ \"negotiator\": {\n+ \"version\": \"0.6.1\",\n+ \"resolved\": \"https://registry.npmjs.org/negotiator/-/negotiator-0.6.1.tgz\",\n+ \"integrity\": \"sha1-KzJxhOiZIQEXeyhWP7XnECrNDKk=\"\n+ },\n+ \"on-finished\": {\n+ \"version\": \"2.3.0\",\n+ \"resolved\": \"https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz\",\n+ \"integrity\": \"sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=\",\n+ \"requires\": {\n+ \"ee-first\": \"1.1.1\"\n+ }\n+ },\n+ \"optimist\": {\n+ \"version\": \"0.6.1\",\n+ \"resolved\": \"https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz\",\n+ \"integrity\": \"sha1-2j6nRob6IaGaERwybpDrFaAZZoY=\",\n+ \"requires\": {\n+ \"minimist\": \"~0.0.1\",\n+ \"wordwrap\": \"~0.0.2\"\n+ }\n+ },\n+ \"parseurl\": {\n+ \"version\": \"1.3.2\",\n+ \"resolved\": \"https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz\",\n+ \"integrity\": \"sha1-/CidTtiZMRlGDBViUyYs3I3mW/M=\"\n+ },\n+ \"path-to-regexp\": {\n+ \"version\": \"0.1.7\",\n+ \"resolved\": \"https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz\",\n+ \"integrity\": \"sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=\"\n+ },\n+ \"proxy-addr\": {\n+ \"version\": \"2.0.4\",\n+ \"resolved\": \"https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.4.tgz\",\n+ \"integrity\": \"sha512-5erio2h9jp5CHGwcybmxmVqHmnCBZeewlfJ0pex+UW7Qny7OOZXTtH56TGNyBizkgiOwhJtMKrVzDTeKcySZwA==\",\n+ \"requires\": {\n+ \"forwarded\": \"~0.1.2\",\n+ \"ipaddr.js\": \"1.8.0\"\n+ }\n+ },\n+ \"qs\": {\n+ \"version\": \"6.5.2\",\n+ \"resolved\": \"https://registry.npmjs.org/qs/-/qs-6.5.2.tgz\",\n+ \"integrity\": \"sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==\"\n+ },\n+ \"range-parser\": {\n+ \"version\": \"1.2.0\",\n+ \"resolved\": \"https://registry.npmjs.org/range-parser/-/range-parser-1.2.0.tgz\",\n+ \"integrity\": \"sha1-9JvmtIeJTdxA3MlKMi9hEJLgDV4=\"\n+ },\n+ \"raw-body\": {\n+ \"version\": \"2.3.3\",\n+ \"resolved\": \"https://registry.npmjs.org/raw-body/-/raw-body-2.3.3.tgz\",\n+ \"integrity\": \"sha512-9esiElv1BrZoI3rCDuOuKCBRbuApGGaDPQfjSflGxdy4oyzqghxu6klEkkVIvBje+FF0BX9coEv8KqW6X/7njw==\",\n+ \"requires\": {\n+ \"bytes\": \"3.0.0\",\n+ \"http-errors\": \"1.6.3\",\n+ \"iconv-lite\": \"0.4.23\",\n+ \"unpipe\": \"1.0.0\"\n+ }\n+ },\n+ \"redis\": {\n+ \"version\": \"2.8.0\",\n+ \"resolved\": \"https://registry.npmjs.org/redis/-/redis-2.8.0.tgz\",\n+ \"integrity\": \"sha512-M1OkonEQwtRmZv4tEWF2VgpG0JWJ8Fv1PhlgT5+B+uNq2cA3Rt1Yt/ryoR+vQNOQcIEgdCdfH0jr3bDpihAw1A==\",\n+ \"requires\": {\n+ \"double-ended-queue\": \"^2.1.0-0\",\n+ \"redis-commands\": \"^1.2.0\",\n+ \"redis-parser\": \"^2.6.0\"\n+ },\n+ \"dependencies\": {\n+ \"redis-commands\": {\n+ \"version\": \"1.4.0\",\n+ \"resolved\": \"https://registry.npmjs.org/redis-commands/-/redis-commands-1.4.0.tgz\",\n+ \"integrity\": \"sha512-cu8EF+MtkwI4DLIT0x9P8qNTLFhQD4jLfxLR0cCNkeGzs87FN6879JOJwNQR/1zD7aSYNbU0hgsV9zGY71Itvw==\"\n+ },\n+ \"redis-parser\": {\n+ \"version\": \"2.6.0\",\n+ \"resolved\": \"https://registry.npmjs.org/redis-parser/-/redis-parser-2.6.0.tgz\",\n+ \"integrity\": \"sha1-Uu0J2srBCPGmMcB+m2mUHnoZUEs=\"\n+ }\n+ }\n+ },\n+ \"redis-commands\": {\n+ \"version\": \"1.5.0\",\n+ \"resolved\": \"https://registry.npmjs.org/redis-commands/-/redis-commands-1.5.0.tgz\",\n+ \"integrity\": \"sha512-6KxamqpZ468MeQC3bkWmCB1fp56XL64D4Kf0zJSwDZbVLLm7KFkoIcHrgRvQ+sk8dnhySs7+yBg94yIkAK7aJg==\"\n+ },\n+ \"redis-parser\": {\n+ \"version\": \"2.6.0\",\n+ \"resolved\": \"https://registry.npmjs.org/redis-parser/-/redis-parser-2.6.0.tgz\",\n+ \"integrity\": \"sha1-Uu0J2srBCPGmMcB+m2mUHnoZUEs=\"\n+ },\n+ \"safe-buffer\": {\n+ \"version\": \"5.1.2\",\n+ \"resolved\": \"https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz\",\n+ \"integrity\": \"sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==\"\n+ },\n+ \"safer-buffer\": {\n+ \"version\": \"2.1.2\",\n+ \"resolved\": \"https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz\",\n+ \"integrity\": \"sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==\"\n+ },\n+ \"secure-random-string\": {\n+ \"version\": \"1.1.0\",\n+ \"resolved\": \"https://registry.npmjs.org/secure-random-string/-/secure-random-string-1.1.0.tgz\",\n+ \"integrity\": \"sha512-V/h8jqoz58zklNGybVhP++cWrxEPXlLM/6BeJ4e0a8zlb4BsbYRzFs16snrxByPa5LUxCVTD3M6EYIVIHR1fAg==\"\n+ },\n+ \"send\": {\n+ \"version\": \"0.16.2\",\n+ \"resolved\": \"https://registry.npmjs.org/send/-/send-0.16.2.tgz\",\n+ \"integrity\": \"sha512-E64YFPUssFHEFBvpbbjr44NCLtI1AohxQ8ZSiJjQLskAdKuriYEP6VyGEsRDH8ScozGpkaX1BGvhanqCwkcEZw==\",\n+ \"requires\": {\n+ \"debug\": \"2.6.9\",\n+ \"depd\": \"~1.1.2\",\n+ \"destroy\": \"~1.0.4\",\n+ \"encodeurl\": \"~1.0.2\",\n+ \"escape-html\": \"~1.0.3\",\n+ \"etag\": \"~1.8.1\",\n+ \"fresh\": \"0.5.2\",\n+ \"http-errors\": \"~1.6.2\",\n+ \"mime\": \"1.4.1\",\n+ \"ms\": \"2.0.0\",\n+ \"on-finished\": \"~2.3.0\",\n+ \"range-parser\": \"~1.2.0\",\n+ \"statuses\": \"~1.4.0\"\n+ }\n+ },\n+ \"serve-static\": {\n+ \"version\": \"1.13.2\",\n+ \"resolved\": \"https://registry.npmjs.org/serve-static/-/serve-static-1.13.2.tgz\",\n+ \"integrity\": \"sha512-p/tdJrO4U387R9oMjb1oj7qSMaMfmOyd4j9hOFoxZe2baQszgHcSWjuya/CiT5kgZZKRudHNOA0pYXOl8rQ5nw==\",\n+ \"requires\": {\n+ \"encodeurl\": \"~1.0.2\",\n+ \"escape-html\": \"~1.0.3\",\n+ \"parseurl\": \"~1.3.2\",\n+ \"send\": \"0.16.2\"\n+ }\n+ },\n+ \"setprototypeof\": {\n+ \"version\": \"1.1.0\",\n+ \"resolved\": \"https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz\",\n+ \"integrity\": \"sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==\"\n+ },\n+ \"source-map\": {\n+ \"version\": \"0.6.1\",\n+ \"resolved\": \"https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz\",\n+ \"integrity\": \"sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==\"\n+ },\n+ \"statuses\": {\n+ \"version\": \"1.4.0\",\n+ \"resolved\": \"https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz\",\n+ \"integrity\": \"sha512-zhSCtt8v2NDrRlPQpCNtw/heZLtfUDqxBM1udqikb/Hbk52LK4nQSwr10u77iopCW5LsyHpuXS0GnEc48mLeew==\"\n+ },\n+ \"type-is\": {\n+ \"version\": \"1.6.16\",\n+ \"resolved\": \"https://registry.npmjs.org/type-is/-/type-is-1.6.16.tgz\",\n+ \"integrity\": \"sha512-HRkVv/5qY2G6I8iab9cI7v1bOIdhm94dVjQCPFElW9W+3GeDOSHmy2EBYe4VTApuzolPcmgFTN3ftVJRKR2J9Q==\",\n+ \"requires\": {\n+ \"media-typer\": \"0.3.0\",\n+ \"mime-types\": \"~2.1.18\"\n+ }\n+ },\n+ \"uglify-js\": {\n+ \"version\": \"3.5.9\",\n+ \"resolved\": \"https://registry.npmjs.org/uglify-js/-/uglify-js-3.5.9.tgz\",\n+ \"integrity\": \"sha512-WpT0RqsDtAWPNJK955DEnb6xjymR8Fn0OlK4TT4pS0ASYsVPqr5ELhgwOwLCP5J5vHeJ4xmMmz3DEgdqC10JeQ==\",\n+ \"optional\": true,\n+ \"requires\": {\n+ \"commander\": \"~2.20.0\",\n+ \"source-map\": \"~0.6.1\"\n+ }\n+ },\n+ \"unpipe\": {\n+ \"version\": \"1.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz\",\n+ \"integrity\": \"sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=\"\n+ },\n+ \"utils-merge\": {\n+ \"version\": \"1.0.1\",\n+ \"resolved\": \"https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz\",\n+ \"integrity\": \"sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=\"\n+ },\n+ \"vary\": {\n+ \"version\": \"1.1.2\",\n+ \"resolved\": \"https://registry.npmjs.org/vary/-/vary-1.1.2.tgz\",\n+ \"integrity\": \"sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=\"\n+ },\n+ \"walk\": {\n+ \"version\": \"2.3.9\",\n+ \"resolved\": \"https://registry.npmjs.org/walk/-/walk-2.3.9.tgz\",\n+ \"integrity\": \"sha1-MbTbZnjyrgHDnqn7hyWpAx5Vins=\",\n+ \"requires\": {\n+ \"foreachasync\": \"^3.0.0\"\n+ }\n+ },\n+ \"wordwrap\": {\n+ \"version\": \"0.0.3\",\n+ \"resolved\": \"https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz\",\n+ \"integrity\": \"sha1-o9XabNXAvAAI03I0u68b7WMFkQc=\"\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/node/package.json",
"diff": "+{\n+ \"name\": \"nodedum\",\n+ \"version\": \"1.0.0\",\n+ \"description\": \"\",\n+ \"main\": \"index.js\",\n+ \"scripts\": {\n+ \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n+ },\n+ \"author\": \"\",\n+ \"license\": \"ISC\",\n+ \"dependencies\": {\n+ \"express\": \"^4.16.4\",\n+ \"hbs\": \"^4.0.4\",\n+ \"redis\": \"^2.8.0\",\n+ \"redis-commands\": \"^1.2.0\",\n+ \"redis-parser\": \"^2.6.0\",\n+ \"secure-random-string\": \"^1.1.0\"\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/network/BUILD",
"new_path": "test/benchmarks/network/BUILD",
"diff": "@@ -15,6 +15,7 @@ go_test(\nsrcs = [\n\"httpd_test.go\",\n\"iperf_test.go\",\n+ \"node_test.go\",\n],\nlibrary = \":network\",\ntags = [\n"
}
] | Go | Apache License 2.0 | google/gvisor | Port node benchmark.
PiperOrigin-RevId: 323810235 |
259,975 | 29.07.2020 10:05:46 | 25,200 | 1715896fc81fce0302e790186302d7460838a918 | Port fio benchmark | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/fio/Dockerfile",
"diff": "+FROM ubuntu:18.04\n+\n+RUN set -x \\\n+ && apt-get update \\\n+ && apt-get install -y \\\n+ fio \\\n+ && rm -rf /var/lib/apt/lists/*\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/fs/BUILD",
"new_path": "test/benchmarks/fs/BUILD",
"diff": "@@ -12,12 +12,19 @@ go_library(\ngo_test(\nname = \"fs_test\",\nsize = \"large\",\n- srcs = [\"bazel_test.go\"],\n+ srcs = [\n+ \"bazel_test.go\",\n+ \"fio_test.go\",\n+ ],\nlibrary = \":fs\",\ntags = [\n# Requires docker and runsc to be configured before test runs.\n\"local\",\n\"manual\",\n],\n- deps = [\"//pkg/test/dockerutil\"],\n+ deps = [\n+ \"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/harness\",\n+ \"@com_github_docker_docker//api/types/mount:go_default_library\",\n+ ],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/fs/bazel_test.go",
"new_path": "test/benchmarks/fs/bazel_test.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"testing\"\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n+ \"gvisor.dev/gvisor/test/benchmarks/harness\"\n)\n// Note: CleanCache versions of this test require running with root permissions.\n@@ -77,8 +78,8 @@ func BenchmarkABSL(b *testing.B) {\nb.StopTimer()\n// Drop Caches for clear cache runs.\nif bm.clearCache {\n- if out, err := machine.RunCommand(\"/bin/sh\", \"-c\", \"sync && sysctl vm.drop_caches=3\"); err != nil {\n- b.Skipf(\"failed to drop caches: %v %s. You probably need root.\", err, out)\n+ if err := harness.DropCaches(machine); err != nil {\n+ b.Skipf(\"failed to drop caches: %v. You probably need root.\", err)\n}\n}\nb.StartTimer()\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/benchmarks/fs/fio_test.go",
"diff": "+// Copyright 2020 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+package fs\n+\n+import (\n+ \"context\"\n+ \"encoding/json\"\n+ \"fmt\"\n+ \"path/filepath\"\n+ \"strconv\"\n+ \"strings\"\n+ \"testing\"\n+\n+ \"github.com/docker/docker/api/types/mount\"\n+ \"gvisor.dev/gvisor/pkg/test/dockerutil\"\n+ \"gvisor.dev/gvisor/test/benchmarks/harness\"\n+)\n+\n+type fioTestCase struct {\n+ test string // test to run: read, write, randread, randwrite.\n+ size string // total size to be read/written of format N[GMK] (e.g. 5G).\n+ blocksize string // blocksize to be read/write of format N[GMK] (e.g. 4K).\n+ iodepth int // iodepth for reads/writes.\n+ time int // time to run the test in seconds, usually for rand(read/write).\n+}\n+\n+// makeCmdFromTestcase makes a fio command.\n+func (f *fioTestCase) makeCmdFromTestcase(filename string) []string {\n+ cmd := []string{\"fio\", \"--output-format=json\", \"--ioengine=sync\"}\n+ cmd = append(cmd, fmt.Sprintf(\"--name=%s\", f.test))\n+ cmd = append(cmd, fmt.Sprintf(\"--size=%s\", f.size))\n+ cmd = append(cmd, fmt.Sprintf(\"--blocksize=%s\", f.blocksize))\n+ cmd = append(cmd, fmt.Sprintf(\"--filename=%s\", filename))\n+ cmd = append(cmd, fmt.Sprintf(\"--iodepth=%d\", f.iodepth))\n+ cmd = append(cmd, fmt.Sprintf(\"--rw=%s\", f.test))\n+ if f.time != 0 {\n+ cmd = append(cmd, \"--time_based\")\n+ cmd = append(cmd, fmt.Sprintf(\"--runtime=%d\", f.time))\n+ }\n+ return cmd\n+}\n+\n+// BenchmarkFio runs fio on the runtime under test. There are 4 basic test\n+// cases each run on a tmpfs mount and a bind mount. Fio requires root so that\n+// caches can be dropped.\n+func BenchmarkFio(b *testing.B) {\n+ testCases := []fioTestCase{\n+ fioTestCase{\n+ test: \"write\",\n+ size: \"5G\",\n+ blocksize: \"1M\",\n+ iodepth: 4,\n+ },\n+ fioTestCase{\n+ test: \"read\",\n+ size: \"5G\",\n+ blocksize: \"1M\",\n+ iodepth: 4,\n+ },\n+ fioTestCase{\n+ test: \"randwrite\",\n+ size: \"5G\",\n+ blocksize: \"4K\",\n+ iodepth: 4,\n+ time: 30,\n+ },\n+ fioTestCase{\n+ test: \"randread\",\n+ size: \"5G\",\n+ blocksize: \"4K\",\n+ iodepth: 4,\n+ time: 30,\n+ },\n+ }\n+\n+ machine, err := h.GetMachine()\n+ if err != nil {\n+ b.Fatalf(\"failed to get machine with: %v\", err)\n+ }\n+ defer machine.CleanUp()\n+\n+ for _, fsType := range []mount.Type{mount.TypeBind, mount.TypeTmpfs} {\n+ for _, tc := range testCases {\n+ testName := strings.Title(tc.test) + strings.Title(string(fsType))\n+ b.Run(testName, func(b *testing.B) {\n+ ctx := context.Background()\n+ container := machine.GetContainer(ctx, b)\n+ defer container.CleanUp(ctx)\n+\n+ // Directory and filename inside container where fio will read/write.\n+ outdir := \"/data\"\n+ outfile := filepath.Join(outdir, \"test.txt\")\n+\n+ // Make the required mount and grab a cleanup for bind mounts\n+ // as they are backed by a temp directory (mktemp).\n+ mnt, mountCleanup, err := makeMount(machine, fsType, outdir)\n+ if err != nil {\n+ b.Fatalf(\"failed to make mount: %v\", err)\n+ }\n+ defer mountCleanup()\n+ cmd := tc.makeCmdFromTestcase(outfile)\n+\n+ // Start the container with the mount.\n+ if err := container.Spawn(\n+ ctx,\n+ dockerutil.RunOpts{\n+ Image: \"benchmarks/fio\",\n+ Mounts: []mount.Mount{\n+ mnt,\n+ },\n+ },\n+ // Sleep on the order of b.N.\n+ \"sleep\", fmt.Sprintf(\"%d\", 1000*b.N),\n+ ); err != nil {\n+ b.Fatalf(\"failed to start fio container with: %v\", err)\n+ }\n+\n+ // For reads, we need a file to read so make one inside the container.\n+ if strings.Contains(tc.test, \"read\") {\n+ fallocateCmd := fmt.Sprintf(\"fallocate -l %s %s\", tc.size, outfile)\n+ if out, err := container.Exec(ctx, dockerutil.ExecOpts{},\n+ strings.Split(fallocateCmd, \" \")...); err != nil {\n+ b.Fatalf(\"failed to create readable file on mount: %v, %s\", err, out)\n+ }\n+ }\n+\n+ // Drop caches just before running.\n+ if err := harness.DropCaches(machine); err != nil {\n+ b.Skipf(\"failed to drop caches with %v. You probably need root.\", err)\n+ }\n+ container.RestartProfiles()\n+ b.ResetTimer()\n+ for i := 0; i < b.N; i++ {\n+ // Run fio.\n+ data, err := container.Exec(ctx, dockerutil.ExecOpts{}, cmd...)\n+ if err != nil {\n+ b.Fatalf(\"failed to run cmd %v: %v\", cmd, err)\n+ }\n+ b.StopTimer()\n+ // Parse the output and report the metrics.\n+ isRead := strings.Contains(tc.test, \"read\")\n+ bw, err := parseBandwidth(data, isRead)\n+ if err != nil {\n+ b.Fatalf(\"failed to parse bandwidth from %s with: %v\", data, err)\n+ }\n+ b.ReportMetric(bw, \"bandwidth\") // in b/s.\n+\n+ iops, err := parseIOps(data, isRead)\n+ if err != nil {\n+ b.Fatalf(\"failed to parse iops from %s with: %v\", data, err)\n+ }\n+ b.ReportMetric(iops, \"iops\")\n+ // If b.N is used (i.e. we run for an hour), we should drop caches\n+ // after each run.\n+ if err := harness.DropCaches(machine); err != nil {\n+ b.Fatalf(\"failed to drop caches: %v\", err)\n+ }\n+ b.StartTimer()\n+ }\n+ })\n+ }\n+ }\n+}\n+\n+// makeMount makes a mount and cleanup based on the requested type. Bind\n+// and volume mounts are backed by a temp directory made with mktemp.\n+// tmpfs mounts require no such backing and are just made.\n+// It is up to the caller to call the returned cleanup.\n+func makeMount(machine harness.Machine, mountType mount.Type, target string) (mount.Mount, func(), error) {\n+ switch mountType {\n+ case mount.TypeVolume, mount.TypeBind:\n+ dir, err := machine.RunCommand(\"mktemp\", \"-d\")\n+ if err != nil {\n+ return mount.Mount{}, func() {}, fmt.Errorf(\"failed to create tempdir: %v\", err)\n+ }\n+ dir = strings.TrimSuffix(dir, \"\\n\")\n+\n+ out, err := machine.RunCommand(\"chmod\", \"777\", dir)\n+ if err != nil {\n+ machine.RunCommand(\"rm\", \"-rf\", dir)\n+ return mount.Mount{}, func() {}, fmt.Errorf(\"failed modify directory: %v %s\", err, out)\n+ }\n+ return mount.Mount{\n+ Target: target,\n+ Source: dir,\n+ Type: mount.TypeBind,\n+ }, func() { machine.RunCommand(\"rm\", \"-rf\", dir) }, nil\n+ case mount.TypeTmpfs:\n+ return mount.Mount{\n+ Target: target,\n+ Type: mount.TypeTmpfs,\n+ }, func() {}, nil\n+ default:\n+ return mount.Mount{}, func() {}, fmt.Errorf(\"illegal mount time not supported: %v\", mountType)\n+ }\n+}\n+\n+// parseBandwidth reports the bandwidth in b/s.\n+func parseBandwidth(data string, isRead bool) (float64, error) {\n+ if isRead {\n+ result, err := parseFioJSON(data, \"read\", \"bw\")\n+ if err != nil {\n+ return 0, err\n+ }\n+ return 1024 * result, nil\n+ }\n+ result, err := parseFioJSON(data, \"write\", \"bw\")\n+ if err != nil {\n+ return 0, err\n+ }\n+ return 1024 * result, nil\n+}\n+\n+// parseIOps reports the write IO per second metric.\n+func parseIOps(data string, isRead bool) (float64, error) {\n+ if isRead {\n+ return parseFioJSON(data, \"read\", \"iops\")\n+ }\n+ return parseFioJSON(data, \"write\", \"iops\")\n+}\n+\n+// fioResult is for parsing FioJSON.\n+type fioResult struct {\n+ Jobs []fioJob\n+}\n+\n+// fioJob is for parsing FioJSON.\n+type fioJob map[string]json.RawMessage\n+\n+// fioMetrics is for parsing FioJSON.\n+type fioMetrics map[string]json.RawMessage\n+\n+// parseFioJSON parses data and grabs \"op\" (read or write) and \"metric\"\n+// (bw or iops) from the JSON.\n+func parseFioJSON(data, op, metric string) (float64, error) {\n+ var result fioResult\n+ if err := json.Unmarshal([]byte(data), &result); err != nil {\n+ return 0, fmt.Errorf(\"could not unmarshal data: %v\", err)\n+ }\n+\n+ if len(result.Jobs) < 1 {\n+ return 0, fmt.Errorf(\"no jobs present to parse\")\n+ }\n+\n+ var metrics fioMetrics\n+ if err := json.Unmarshal(result.Jobs[0][op], &metrics); err != nil {\n+ return 0, fmt.Errorf(\"could not unmarshal jobs: %v\", err)\n+ }\n+\n+ if _, ok := metrics[metric]; !ok {\n+ return 0, fmt.Errorf(\"no metric found for op: %s\", op)\n+ }\n+ return strconv.ParseFloat(string(metrics[metric]), 64)\n+}\n+\n+// TestParsers tests that the parsers work on sampleData.\n+func TestParsers(t *testing.T) {\n+ sampleData := `\n+{\n+ \"fio version\" : \"fio-3.1\",\n+ \"timestamp\" : 1554837456,\n+ \"timestamp_ms\" : 1554837456621,\n+ \"time\" : \"Tue Apr 9 19:17:36 2019\",\n+ \"jobs\" : [\n+ {\n+ \"jobname\" : \"test\",\n+ \"groupid\" : 0,\n+ \"error\" : 0,\n+ \"eta\" : 2147483647,\n+ \"elapsed\" : 1,\n+ \"job options\" : {\n+ \"name\" : \"test\",\n+ \"ioengine\" : \"sync\",\n+ \"size\" : \"1073741824\",\n+ \"filename\" : \"/disk/file.dat\",\n+ \"iodepth\" : \"4\",\n+ \"bs\" : \"4096\",\n+ \"rw\" : \"write\"\n+ },\n+ \"read\" : {\n+ \"io_bytes\" : 0,\n+ \"io_kbytes\" : 0,\n+ \"bw\" : 123456,\n+ \"iops\" : 1234.5678,\n+ \"runtime\" : 0,\n+ \"total_ios\" : 0,\n+ \"short_ios\" : 0,\n+ \"bw_min\" : 0,\n+ \"bw_max\" : 0,\n+ \"bw_agg\" : 0.000000,\n+ \"bw_mean\" : 0.000000,\n+ \"bw_dev\" : 0.000000,\n+ \"bw_samples\" : 0,\n+ \"iops_min\" : 0,\n+ \"iops_max\" : 0,\n+ \"iops_mean\" : 0.000000,\n+ \"iops_stddev\" : 0.000000,\n+ \"iops_samples\" : 0\n+ },\n+ \"write\" : {\n+ \"io_bytes\" : 1073741824,\n+ \"io_kbytes\" : 1048576,\n+ \"bw\" : 1753471,\n+ \"iops\" : 438367.892977,\n+ \"runtime\" : 598,\n+ \"total_ios\" : 262144,\n+ \"bw_min\" : 1731120,\n+ \"bw_max\" : 1731120,\n+ \"bw_agg\" : 98.725328,\n+ \"bw_mean\" : 1731120.000000,\n+ \"bw_dev\" : 0.000000,\n+ \"bw_samples\" : 1,\n+ \"iops_min\" : 432780,\n+ \"iops_max\" : 432780,\n+ \"iops_mean\" : 432780.000000,\n+ \"iops_stddev\" : 0.000000,\n+ \"iops_samples\" : 1\n+ }\n+ }\n+ ]\n+}\n+`\n+ // WriteBandwidth.\n+ got, err := parseBandwidth(sampleData, false)\n+ var want float64 = 1753471.0 * 1024\n+ if err != nil {\n+ t.Fatalf(\"parse failed with err: %v\", err)\n+ } else if got != want {\n+ t.Fatalf(\"got: %f, want: %f\", got, want)\n+ }\n+\n+ // ReadBandwidth.\n+ got, err = parseBandwidth(sampleData, true)\n+ want = 123456 * 1024\n+ if err != nil {\n+ t.Fatalf(\"parse failed with err: %v\", err)\n+ } else if got != want {\n+ t.Fatalf(\"got: %f, want: %f\", got, want)\n+ }\n+\n+ // WriteIOps.\n+ got, err = parseIOps(sampleData, false)\n+ want = 438367.892977\n+ if err != nil {\n+ t.Fatalf(\"parse failed with err: %v\", err)\n+ } else if got != want {\n+ t.Fatalf(\"got: %f, want: %f\", got, want)\n+ }\n+\n+ // ReadIOps.\n+ got, err = parseIOps(sampleData, true)\n+ want = 1234.5678\n+ if err != nil {\n+ t.Fatalf(\"parse failed with err: %v\", err)\n+ } else if got != want {\n+ t.Fatalf(\"got: %f, want: %f\", got, want)\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Port fio benchmark
PiperOrigin-RevId: 323810654 |
259,885 | 29.07.2020 14:56:14 | 25,200 | 4cd4759238655e35c8dc63723f4e55014b5ea9ea | Force registration for EPOLLHUP, not EPOLLRDHUP, in vfs2's epoll.
Compare Linux's fs/eventpoll.c:do_epoll_ctl(). I don't know where EPOLLRDHUP
came from. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/epoll.go",
"new_path": "pkg/sentry/vfs/epoll.go",
"diff": "@@ -186,7 +186,7 @@ func (ep *EpollInstance) AddInterest(file *FileDescription, num int32, event lin\n}\n// Register interest in file.\n- mask := event.Events | linux.EPOLLERR | linux.EPOLLRDHUP\n+ mask := event.Events | linux.EPOLLERR | linux.EPOLLHUP\nepi := &epollInterest{\nepoll: ep,\nkey: key,\n@@ -257,7 +257,7 @@ func (ep *EpollInstance) ModifyInterest(file *FileDescription, num int32, event\n}\n// Update epi for the next call to ep.ReadEvents().\n- mask := event.Events | linux.EPOLLERR | linux.EPOLLRDHUP\n+ mask := event.Events | linux.EPOLLERR | linux.EPOLLHUP\nep.mu.Lock()\nepi.mask = mask\nepi.userData = event.Data\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/epoll.cc",
"new_path": "test/syscalls/linux/epoll.cc",
"diff": "@@ -422,6 +422,28 @@ TEST(EpollTest, CloseFile) {\nSyscallSucceedsWithValue(0));\n}\n+TEST(EpollTest, PipeReaderHupAfterWriterClosed) {\n+ auto epollfd = ASSERT_NO_ERRNO_AND_VALUE(NewEpollFD());\n+ int pipefds[2];\n+ ASSERT_THAT(pipe(pipefds), SyscallSucceeds());\n+ FileDescriptor rfd(pipefds[0]);\n+ FileDescriptor wfd(pipefds[1]);\n+\n+ ASSERT_NO_ERRNO(RegisterEpollFD(epollfd.get(), rfd.get(), 0, kMagicConstant));\n+ struct epoll_event result[kFDsPerEpoll];\n+ // Initially, rfd should not generate any events of interest.\n+ ASSERT_THAT(epoll_wait(epollfd.get(), result, kFDsPerEpoll, 0),\n+ SyscallSucceedsWithValue(0));\n+ // Close the write end of the pipe.\n+ wfd.reset();\n+ // rfd should now generate EPOLLHUP, which EPOLL_CTL_ADD unconditionally adds\n+ // to the set of events of interest.\n+ ASSERT_THAT(epoll_wait(epollfd.get(), result, kFDsPerEpoll, 0),\n+ SyscallSucceedsWithValue(1));\n+ EXPECT_EQ(result[0].events, EPOLLHUP);\n+ EXPECT_EQ(result[0].data.u64, kMagicConstant);\n+}\n+\n} // namespace\n} // namespace testing\n"
}
] | Go | Apache License 2.0 | google/gvisor | Force registration for EPOLLHUP, not EPOLLRDHUP, in vfs2's epoll.
Compare Linux's fs/eventpoll.c:do_epoll_ctl(). I don't know where EPOLLRDHUP
came from.
PiperOrigin-RevId: 323874419 |
259,858 | 30.07.2020 09:23:44 | 25,200 | 84496b3a619def2db0e25ab41f029823621bc713 | Disable consistently failing test. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_inet_loopback_nogotsan.cc",
"new_path": "test/syscalls/linux/socket_inet_loopback_nogotsan.cc",
"diff": "@@ -82,8 +82,11 @@ using SocketInetLoopbackTest = ::testing::TestWithParam<TestParam>;\n// This test verifies that connect returns EADDRNOTAVAIL if all local ephemeral\n// ports are already in use for a given destination ip/port.\n+//\n// We disable S/R because this test creates a large number of sockets.\n-TEST_P(SocketInetLoopbackTest, TestTCPPortExhaustion_NoRandomSave) {\n+//\n+// FIXME(b/162475855): This test is failing reliably.\n+TEST_P(SocketInetLoopbackTest, DISABLED_TestTCPPortExhaustion_NoRandomSave) {\nauto const& param = GetParam();\nTestAddress const& listener = param.listener;\nTestAddress const& connector = param.connector;\n"
}
] | Go | Apache License 2.0 | google/gvisor | Disable consistently failing test.
PiperOrigin-RevId: 324017310 |
259,858 | 30.07.2020 09:49:19 | 25,200 | 0d7c87ad014aa8eb931a5dcb970d736ce00d4b32 | Double the number of jobs used by RBE. | [
{
"change_type": "MODIFY",
"old_path": ".bazelrc",
"new_path": ".bazelrc",
"diff": "@@ -50,14 +50,14 @@ build:remote --extra_toolchains=//tools/bazeldefs:cc-toolchain-clang-x86_64-defa\nbuild:remote --extra_execution_platforms=//tools/bazeldefs:rbe_ubuntu1604\nbuild:remote --platforms=//tools/bazeldefs:rbe_ubuntu1604\nbuild:remote --crosstool_top=@rbe_default//cc:toolchain\n-build:remote --jobs=50\n+build:remote --jobs=100\nbuild:remote --remote_timeout=3600\nbuild:remote3 --host_platform=//tools/bazeldefs:rbe_ubuntu1604_bazel3\nbuild:remote3 --extra_toolchains=//tools/bazeldefs:cc-toolchain-clang-x86_64-default_bazel3\nbuild:remote3 --extra_execution_platforms=//tools/bazeldefs:rbe_ubuntu1604_bazel3\nbuild:remote3 --platforms=//tools/bazeldefs:rbe_ubuntu1604_bazel3\nbuild:remote3 --crosstool_top=@rbe_default//cc:toolchain\n-build:remote3 --jobs=50\n+build:remote3 --jobs=100\nbuild:remote3 --remote_timeout=3600\n# Set flags for uploading to BES in order to view results in the Bazel Build\n"
}
] | Go | Apache License 2.0 | google/gvisor | Double the number of jobs used by RBE.
PiperOrigin-RevId: 324022546 |
259,858 | 30.07.2020 09:53:52 | 25,200 | 61b3e05f404a06995cb5da6187958f38af864ff6 | Drop complex awk step. | [
{
"change_type": "MODIFY",
"old_path": "tools/make_release.sh",
"new_path": "tools/make_release.sh",
"diff": "@@ -43,8 +43,7 @@ install_raw() {\n# Copy the raw file & generate a sha512sum.\nname=$(basename \"${binary}\")\ncp -f \"${binary}\" \"${root}/$1\"\n- sha512sum \"${root}/$1/${name}\" | \\\n- awk \"{print $$1 \\\" ${name}\\\"}\" > \"${root}/$1/${name}.sha512\"\n+ (cd \"${root}/$1\" && sha512sum \"${name}\" > \"${name}.sha512\")\ndone\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Drop complex awk step.
PiperOrigin-RevId: 324023425 |
259,858 | 30.07.2020 09:57:02 | 25,200 | cb1a3ba63a4a44cf929bb7a1449e76e7664923ff | Fix merge flow for Go branch. | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/go.yml",
"new_path": ".github/workflows/go.yml",
"diff": "@@ -18,6 +18,7 @@ jobs:\nelse\necho ::set-output has_token=false\nfi\n+ - run: |\njq -nc '{\"state\": \"pending\", \"context\": \"go tests\"}' | \\\ncurl -sL -X POST -d @- \\\n-H \"Content-Type: application/json\" \\\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix merge flow for Go branch.
PiperOrigin-RevId: 324024075 |
259,858 | 30.07.2020 10:05:53 | 25,200 | 6a59e765c32f151a549de967f6b010613a5b9aa0 | Override the test timeout for runtimes. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -155,7 +155,7 @@ syscall-tests: syscall-ptrace-tests syscall-kvm-tests syscall-native-tests\n%-runtime-tests: load-runtimes_%\n@$(call submake,install-test-runtime)\n- @$(call submake,test-runtime TARGETS=\"//test/runtimes:$*\")\n+ @$(call submake,test-runtime OPTIONS=\"--test_timeout=10800\" TARGETS=\"//test/runtimes:$*\")\ndo-tests: runsc\n@$(call submake,run TARGETS=\"//runsc\" ARGS=\"--rootless do true\")\n@@ -370,5 +370,5 @@ configure: ## Configures a single runtime. Requires sudo. Typically called from\n.PHONY: configure\ntest-runtime: ## A convenient wrapper around test that provides the runtime argument. Target must still be provided.\n- @$(call submake,test OPTIONS=\"$(OPTIONS) --test_output=streamed --test_arg=--runtime=$(RUNTIME)\")\n+ @$(call submake,test OPTIONS=\"$(OPTIONS) --test_arg=--runtime=$(RUNTIME)\")\n.PHONY: test-runtime\n"
}
] | Go | Apache License 2.0 | google/gvisor | Override the test timeout for runtimes.
PiperOrigin-RevId: 324026021 |
259,975 | 30.07.2020 10:16:06 | 25,200 | 2775ecd931ec67a8ba68f743b684d88c19d45d44 | Update call in Node benchmark. | [
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/network/node_test.go",
"new_path": "test/benchmarks/network/node_test.go",
"diff": "@@ -73,7 +73,7 @@ func runNode(b *testing.B, requests, concurrency int) {\nif out, err := redis.WaitForOutput(ctx, \"Ready to accept connections\", 3*time.Second); err != nil {\nb.Fatalf(\"failed to start redis server: %v %s\", err, out)\n}\n- redisIP, err := redis.FindIP(ctx)\n+ redisIP, err := redis.FindIP(ctx, false)\nif err != nil {\nb.Fatalf(\"failed to get IP from redis instance: %v\", err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update call in Node benchmark.
PiperOrigin-RevId: 324028183 |
259,860 | 30.07.2020 10:21:12 | 25,200 | c43305731e04ce8d4f2c9b2949c326abc9c2b77e | Fix SETOWN_EX return value.
Return on success should be 0, not size of the struct copied out. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_file.go",
"new_path": "pkg/sentry/syscalls/linux/sys_file.go",
"diff": "@@ -1057,7 +1057,7 @@ func Fcntl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\ncase linux.F_SETOWN_EX:\naddr := args[2].Pointer()\nvar owner linux.FOwnerEx\n- n, err := t.CopyIn(addr, &owner)\n+ _, err := t.CopyIn(addr, &owner)\nif err != nil {\nreturn 0, nil, err\n}\n@@ -1069,21 +1069,21 @@ func Fcntl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\nreturn 0, nil, syserror.ESRCH\n}\na.SetOwnerTask(t, task)\n- return uintptr(n), nil, nil\n+ return 0, nil, nil\ncase linux.F_OWNER_PID:\ntg := t.PIDNamespace().ThreadGroupWithID(kernel.ThreadID(owner.PID))\nif tg == nil {\nreturn 0, nil, syserror.ESRCH\n}\na.SetOwnerThreadGroup(t, tg)\n- return uintptr(n), nil, nil\n+ return 0, nil, nil\ncase linux.F_OWNER_PGRP:\npg := t.PIDNamespace().ProcessGroupWithID(kernel.ProcessGroupID(owner.PID))\nif pg == nil {\nreturn 0, nil, syserror.ESRCH\n}\na.SetOwnerProcessGroup(t, pg)\n- return uintptr(n), nil, nil\n+ return 0, nil, nil\ndefault:\nreturn 0, nil, syserror.EINVAL\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/fd.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/fd.go",
"diff": "@@ -185,11 +185,11 @@ func Fcntl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\nreturn 0, nil, err\ncase linux.F_SETOWN_EX:\nvar owner linux.FOwnerEx\n- n, err := t.CopyIn(args[2].Pointer(), &owner)\n+ _, err := t.CopyIn(args[2].Pointer(), &owner)\nif err != nil {\nreturn 0, nil, err\n}\n- return uintptr(n), nil, setAsyncOwner(t, file, owner.Type, owner.PID)\n+ return 0, nil, setAsyncOwner(t, file, owner.Type, owner.PID)\ncase linux.F_GETPIPE_SZ:\npipefile, ok := file.Impl().(*pipe.VFSPipeFD)\nif !ok {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/fcntl.cc",
"new_path": "test/syscalls/linux/fcntl.cc",
"diff": "@@ -1004,7 +1004,8 @@ TEST(FcntlTest, SetOwnPid) {\npid_t pid;\nEXPECT_THAT(pid = getpid(), SyscallSucceeds());\n- ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN, pid), SyscallSucceeds());\n+ ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN, pid),\n+ SyscallSucceedsWithValue(0));\nEXPECT_THAT(syscall(__NR_fcntl, s.get(), F_GETOWN),\nSyscallSucceedsWithValue(pid));\n@@ -1018,7 +1019,8 @@ TEST(FcntlTest, SetOwnPgrp) {\npid_t pgid;\nEXPECT_THAT(pgid = getpgrp(), SyscallSucceeds());\n- ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN, -pgid), SyscallSucceeds());\n+ ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN, -pgid),\n+ SyscallSucceedsWithValue(0));\n// Verify with F_GETOWN_EX; using F_GETOWN on Linux may incorrectly treat the\n// negative return value as an error, converting the return value to -1 and\n@@ -1038,8 +1040,10 @@ TEST(FcntlTest, SetOwnUnset) {\n// Set and unset pid.\npid_t pid;\nEXPECT_THAT(pid = getpid(), SyscallSucceeds());\n- ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN, pid), SyscallSucceeds());\n- ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN, 0), SyscallSucceeds());\n+ ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN, pid),\n+ SyscallSucceedsWithValue(0));\n+ ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN, 0),\n+ SyscallSucceedsWithValue(0));\nEXPECT_THAT(syscall(__NR_fcntl, s.get(), F_GETOWN),\nSyscallSucceedsWithValue(0));\n@@ -1047,8 +1051,10 @@ TEST(FcntlTest, SetOwnUnset) {\n// Set and unset pgid.\npid_t pgid;\nEXPECT_THAT(pgid = getpgrp(), SyscallSucceeds());\n- ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN, -pgid), SyscallSucceeds());\n- ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN, 0), SyscallSucceeds());\n+ ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN, -pgid),\n+ SyscallSucceedsWithValue(0));\n+ ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN, 0),\n+ SyscallSucceedsWithValue(0));\nEXPECT_THAT(syscall(__NR_fcntl, s.get(), F_GETOWN),\nSyscallSucceedsWithValue(0));\n@@ -1120,7 +1126,7 @@ TEST(FcntlTest, SetOwnExTid) {\nEXPECT_THAT(owner.pid = syscall(__NR_gettid), SyscallSucceeds());\nASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &owner),\n- SyscallSucceeds());\n+ SyscallSucceedsWithValue(0));\nEXPECT_THAT(syscall(__NR_fcntl, s.get(), F_GETOWN),\nSyscallSucceedsWithValue(owner.pid));\n@@ -1136,7 +1142,7 @@ TEST(FcntlTest, SetOwnExPid) {\nEXPECT_THAT(owner.pid = getpid(), SyscallSucceeds());\nASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &owner),\n- SyscallSucceeds());\n+ SyscallSucceedsWithValue(0));\nEXPECT_THAT(syscall(__NR_fcntl, s.get(), F_GETOWN),\nSyscallSucceedsWithValue(owner.pid));\n@@ -1152,7 +1158,7 @@ TEST(FcntlTest, SetOwnExPgrp) {\nEXPECT_THAT(set_owner.pid = getpgrp(), SyscallSucceeds());\nASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &set_owner),\n- SyscallSucceeds());\n+ SyscallSucceedsWithValue(0));\n// Verify with F_GETOWN_EX; using F_GETOWN on Linux may incorrectly treat the\n// negative return value as an error, converting the return value to -1 and\n@@ -1176,10 +1182,10 @@ TEST(FcntlTest, SetOwnExUnset) {\nowner.type = F_OWNER_PID;\nEXPECT_THAT(owner.pid = getpid(), SyscallSucceeds());\nASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &owner),\n- SyscallSucceeds());\n+ SyscallSucceedsWithValue(0));\nowner.pid = 0;\nASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &owner),\n- SyscallSucceeds());\n+ SyscallSucceedsWithValue(0));\nEXPECT_THAT(syscall(__NR_fcntl, s.get(), F_GETOWN),\nSyscallSucceedsWithValue(0));\n@@ -1188,10 +1194,10 @@ TEST(FcntlTest, SetOwnExUnset) {\nowner.type = F_OWNER_PGRP;\nEXPECT_THAT(owner.pid = getpgrp(), SyscallSucceeds());\nASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &owner),\n- SyscallSucceeds());\n+ SyscallSucceedsWithValue(0));\nowner.pid = 0;\nASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &owner),\n- SyscallSucceeds());\n+ SyscallSucceedsWithValue(0));\nEXPECT_THAT(syscall(__NR_fcntl, s.get(), F_GETOWN),\nSyscallSucceedsWithValue(0));\n@@ -1207,7 +1213,7 @@ TEST(FcntlTest, GetOwnExTid) {\nEXPECT_THAT(set_owner.pid = syscall(__NR_gettid), SyscallSucceeds());\nASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &set_owner),\n- SyscallSucceeds());\n+ SyscallSucceedsWithValue(0));\nf_owner_ex got_owner = {};\nASSERT_THAT(syscall(__NR_fcntl, s.get(), F_GETOWN_EX, &got_owner),\n@@ -1225,7 +1231,7 @@ TEST(FcntlTest, GetOwnExPid) {\nEXPECT_THAT(set_owner.pid = getpid(), SyscallSucceeds());\nASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &set_owner),\n- SyscallSucceeds());\n+ SyscallSucceedsWithValue(0));\nf_owner_ex got_owner = {};\nASSERT_THAT(syscall(__NR_fcntl, s.get(), F_GETOWN_EX, &got_owner),\n@@ -1243,7 +1249,7 @@ TEST(FcntlTest, GetOwnExPgrp) {\nEXPECT_THAT(set_owner.pid = getpgrp(), SyscallSucceeds());\nASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &set_owner),\n- SyscallSucceeds());\n+ SyscallSucceedsWithValue(0));\nf_owner_ex got_owner = {};\nASSERT_THAT(syscall(__NR_fcntl, s.get(), F_GETOWN_EX, &got_owner),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix SETOWN_EX return value.
Return on success should be 0, not size of the struct copied out.
PiperOrigin-RevId: 324029193 |
259,891 | 30.07.2020 11:27:47 | 25,200 | bc8201d01bc98e9db4009d250454c5fe73c5d2b4 | Have dockerutil.Wait* respect the context deadline | [
{
"change_type": "MODIFY",
"old_path": "pkg/test/dockerutil/container.go",
"new_path": "pkg/test/dockerutil/container.go",
"diff": "@@ -454,15 +454,19 @@ func (c *Container) Wait(ctx context.Context) error {\n// WaitTimeout waits for the container to exit with a timeout.\nfunc (c *Container) WaitTimeout(ctx context.Context, timeout time.Duration) error {\n- timeoutChan := time.After(timeout)\n+ ctx, cancel := context.WithTimeout(ctx, timeout)\n+ defer cancel()\nstatusChan, errChan := c.client.ContainerWait(ctx, c.id, container.WaitConditionNotRunning)\nselect {\n+ case <-ctx.Done():\n+ if ctx.Err() == context.DeadlineExceeded {\n+ return fmt.Errorf(\"container %s timed out after %v seconds\", c.Name, timeout.Seconds())\n+ }\n+ return nil\ncase err := <-errChan:\nreturn err\ncase <-statusChan:\nreturn nil\n- case <-timeoutChan:\n- return fmt.Errorf(\"container %s timed out after %v seconds\", c.Name, timeout.Seconds())\n}\n}\n@@ -487,6 +491,12 @@ func (c *Container) WaitForOutputSubmatch(ctx context.Context, pattern string, t\n}\nfor exp := time.Now().Add(timeout); time.Now().Before(exp); {\n+ select {\n+ case <-ctx.Done():\n+ return nil, ctx.Err()\n+ default:\n+ }\n+\nc.streams.Conn.SetDeadline(time.Now().Add(50 * time.Millisecond))\n_, err := stdcopy.StdCopy(&c.streamBuf, &c.streamBuf, c.streams.Reader)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Have dockerutil.Wait* respect the context deadline
PiperOrigin-RevId: 324044634 |
260,004 | 30.07.2020 12:48:18 | 25,200 | b00858d075fbc39c6fb2db9f903ac14f197566bd | Use brodcast MAC for broadcast IPv4 packets
When sending packets to a known network's broadcast address, use the
broadcast MAC address.
Test:
stack_test.TestOutgoingSubnetBroadcast
udp_test.TestOutgoingSubnetBroadcast | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/BUILD",
"new_path": "pkg/tcpip/stack/BUILD",
"diff": "@@ -110,6 +110,7 @@ go_test(\n\"//pkg/tcpip/transport/udp\",\n\"//pkg/waiter\",\n\"@com_github_google_go_cmp//cmp:go_default_library\",\n+ \"@com_github_google_go_cmp//cmp/cmpopts:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/route.go",
"new_path": "pkg/tcpip/stack/route.go",
"diff": "@@ -48,6 +48,10 @@ type Route struct {\n// Loop controls where WritePacket should send packets.\nLoop PacketLooping\n+\n+ // directedBroadcast indicates whether this route is sending a directed\n+ // broadcast packet.\n+ directedBroadcast bool\n}\n// makeRoute initializes a new route. It takes ownership of the provided\n@@ -275,6 +279,12 @@ func (r *Route) Stack() *Stack {\nreturn r.ref.stack()\n}\n+// IsBroadcast returns true if the route is to send a broadcast packet.\n+func (r *Route) IsBroadcast() bool {\n+ // Only IPv4 has a notion of broadcast.\n+ return r.directedBroadcast || r.RemoteAddress == header.IPv4Broadcast\n+}\n+\n// ReverseRoute returns new route with given source and destination address.\nfunc (r *Route) ReverseRoute(src tcpip.Address, dst tcpip.Address) Route {\nreturn Route{\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -1284,9 +1284,9 @@ func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, n\ns.mu.RLock()\ndefer s.mu.RUnlock()\n- isBroadcast := remoteAddr == header.IPv4Broadcast\n+ isLocalBroadcast := remoteAddr == header.IPv4Broadcast\nisMulticast := header.IsV4MulticastAddress(remoteAddr) || header.IsV6MulticastAddress(remoteAddr)\n- needRoute := !(isBroadcast || isMulticast || header.IsV6LinkLocalAddress(remoteAddr))\n+ needRoute := !(isLocalBroadcast || isMulticast || header.IsV6LinkLocalAddress(remoteAddr))\nif id != 0 && !needRoute {\nif nic, ok := s.nics[id]; ok && nic.enabled() {\nif ref := s.getRefEP(nic, localAddr, remoteAddr, netProto); ref != nil {\n@@ -1307,9 +1307,16 @@ func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, n\n}\nr := makeRoute(netProto, ref.ep.ID().LocalAddress, remoteAddr, nic.linkEP.LinkAddress(), ref, s.handleLocal && !nic.isLoopback(), multicastLoop && !nic.isLoopback())\n+ r.directedBroadcast = route.Destination.IsBroadcast(remoteAddr)\n+\n+ if len(route.Gateway) > 0 {\nif needRoute {\nr.NextHop = route.Gateway\n}\n+ } else if r.directedBroadcast {\n+ r.RemoteLinkAddress = header.EthernetBroadcastAddress\n+ }\n+\nreturn r, nil\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -27,6 +27,7 @@ import (\n\"time\"\n\"github.com/google/go-cmp/cmp\"\n+ \"github.com/google/go-cmp/cmp/cmpopts\"\n\"gvisor.dev/gvisor/pkg/rand\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n@@ -3418,3 +3419,225 @@ func TestStackSendBufferSizeOption(t *testing.T) {\n})\n}\n}\n+\n+func TestOutgoingSubnetBroadcast(t *testing.T) {\n+ const (\n+ unspecifiedNICID = 0\n+ nicID1 = 1\n+ )\n+\n+ defaultAddr := tcpip.AddressWithPrefix{\n+ Address: header.IPv4Any,\n+ PrefixLen: 0,\n+ }\n+ defaultSubnet := defaultAddr.Subnet()\n+ ipv4Addr := tcpip.AddressWithPrefix{\n+ Address: \"\\xc0\\xa8\\x01\\x3a\",\n+ PrefixLen: 24,\n+ }\n+ ipv4Subnet := ipv4Addr.Subnet()\n+ ipv4SubnetBcast := ipv4Subnet.Broadcast()\n+ ipv4Gateway := tcpip.Address(\"\\xc0\\xa8\\x01\\x01\")\n+ ipv4AddrPrefix31 := tcpip.AddressWithPrefix{\n+ Address: \"\\xc0\\xa8\\x01\\x3a\",\n+ PrefixLen: 31,\n+ }\n+ ipv4Subnet31 := ipv4AddrPrefix31.Subnet()\n+ ipv4Subnet31Bcast := ipv4Subnet31.Broadcast()\n+ ipv4AddrPrefix32 := tcpip.AddressWithPrefix{\n+ Address: \"\\xc0\\xa8\\x01\\x3a\",\n+ PrefixLen: 32,\n+ }\n+ ipv4Subnet32 := ipv4AddrPrefix32.Subnet()\n+ ipv4Subnet32Bcast := ipv4Subnet32.Broadcast()\n+ ipv6Addr := tcpip.AddressWithPrefix{\n+ Address: \"\\x20\\x0a\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\",\n+ PrefixLen: 64,\n+ }\n+ ipv6Subnet := ipv6Addr.Subnet()\n+ ipv6SubnetBcast := ipv6Subnet.Broadcast()\n+ remNetAddr := tcpip.AddressWithPrefix{\n+ Address: \"\\x64\\x0a\\x7b\\x18\",\n+ PrefixLen: 24,\n+ }\n+ remNetSubnet := remNetAddr.Subnet()\n+ remNetSubnetBcast := remNetSubnet.Broadcast()\n+\n+ tests := []struct {\n+ name string\n+ nicAddr tcpip.ProtocolAddress\n+ routes []tcpip.Route\n+ remoteAddr tcpip.Address\n+ expectedRoute stack.Route\n+ }{\n+ // Broadcast to a locally attached subnet populates the broadcast MAC.\n+ {\n+ name: \"IPv4 Broadcast to local subnet\",\n+ nicAddr: tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: ipv4Addr,\n+ },\n+ routes: []tcpip.Route{\n+ {\n+ Destination: ipv4Subnet,\n+ NIC: nicID1,\n+ },\n+ },\n+ remoteAddr: ipv4SubnetBcast,\n+ expectedRoute: stack.Route{\n+ LocalAddress: ipv4Addr.Address,\n+ RemoteAddress: ipv4SubnetBcast,\n+ RemoteLinkAddress: header.EthernetBroadcastAddress,\n+ NetProto: header.IPv4ProtocolNumber,\n+ Loop: stack.PacketOut,\n+ },\n+ },\n+ // Broadcast to a locally attached /31 subnet does not populate the\n+ // broadcast MAC.\n+ {\n+ name: \"IPv4 Broadcast to local /31 subnet\",\n+ nicAddr: tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: ipv4AddrPrefix31,\n+ },\n+ routes: []tcpip.Route{\n+ {\n+ Destination: ipv4Subnet31,\n+ NIC: nicID1,\n+ },\n+ },\n+ remoteAddr: ipv4Subnet31Bcast,\n+ expectedRoute: stack.Route{\n+ LocalAddress: ipv4AddrPrefix31.Address,\n+ RemoteAddress: ipv4Subnet31Bcast,\n+ NetProto: header.IPv4ProtocolNumber,\n+ Loop: stack.PacketOut,\n+ },\n+ },\n+ // Broadcast to a locally attached /32 subnet does not populate the\n+ // broadcast MAC.\n+ {\n+ name: \"IPv4 Broadcast to local /32 subnet\",\n+ nicAddr: tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: ipv4AddrPrefix32,\n+ },\n+ routes: []tcpip.Route{\n+ {\n+ Destination: ipv4Subnet32,\n+ NIC: nicID1,\n+ },\n+ },\n+ remoteAddr: ipv4Subnet32Bcast,\n+ expectedRoute: stack.Route{\n+ LocalAddress: ipv4AddrPrefix32.Address,\n+ RemoteAddress: ipv4Subnet32Bcast,\n+ NetProto: header.IPv4ProtocolNumber,\n+ Loop: stack.PacketOut,\n+ },\n+ },\n+ // IPv6 has no notion of a broadcast.\n+ {\n+ name: \"IPv6 'Broadcast' to local subnet\",\n+ nicAddr: tcpip.ProtocolAddress{\n+ Protocol: header.IPv6ProtocolNumber,\n+ AddressWithPrefix: ipv6Addr,\n+ },\n+ routes: []tcpip.Route{\n+ {\n+ Destination: ipv6Subnet,\n+ NIC: nicID1,\n+ },\n+ },\n+ remoteAddr: ipv6SubnetBcast,\n+ expectedRoute: stack.Route{\n+ LocalAddress: ipv6Addr.Address,\n+ RemoteAddress: ipv6SubnetBcast,\n+ NetProto: header.IPv6ProtocolNumber,\n+ Loop: stack.PacketOut,\n+ },\n+ },\n+ // Broadcast to a remote subnet in the route table is send to the next-hop\n+ // gateway.\n+ {\n+ name: \"IPv4 Broadcast to remote subnet\",\n+ nicAddr: tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: ipv4Addr,\n+ },\n+ routes: []tcpip.Route{\n+ {\n+ Destination: remNetSubnet,\n+ Gateway: ipv4Gateway,\n+ NIC: nicID1,\n+ },\n+ },\n+ remoteAddr: remNetSubnetBcast,\n+ expectedRoute: stack.Route{\n+ LocalAddress: ipv4Addr.Address,\n+ RemoteAddress: remNetSubnetBcast,\n+ NextHop: ipv4Gateway,\n+ NetProto: header.IPv4ProtocolNumber,\n+ Loop: stack.PacketOut,\n+ },\n+ },\n+ // Broadcast to an unknown subnet follows the default route. Note that this\n+ // is essentially just routing an unknown destination IP, because w/o any\n+ // subnet prefix information a subnet broadcast address is just a normal IP.\n+ {\n+ name: \"IPv4 Broadcast to unknown subnet\",\n+ nicAddr: tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: ipv4Addr,\n+ },\n+ routes: []tcpip.Route{\n+ {\n+ Destination: defaultSubnet,\n+ Gateway: ipv4Gateway,\n+ NIC: nicID1,\n+ },\n+ },\n+ remoteAddr: remNetSubnetBcast,\n+ expectedRoute: stack.Route{\n+ LocalAddress: ipv4Addr.Address,\n+ RemoteAddress: remNetSubnetBcast,\n+ NextHop: ipv4Gateway,\n+ NetProto: header.IPv4ProtocolNumber,\n+ Loop: stack.PacketOut,\n+ },\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{ipv4.NewProtocol(), ipv6.NewProtocol()},\n+ })\n+ ep := channel.New(0, defaultMTU, \"\")\n+ if err := s.CreateNIC(nicID1, ep); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID1, err)\n+ }\n+ if err := s.AddProtocolAddress(nicID1, test.nicAddr); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %+v): %s\", nicID1, test.nicAddr, err)\n+ }\n+\n+ s.SetRouteTable(test.routes)\n+\n+ var netProto tcpip.NetworkProtocolNumber\n+ switch l := len(test.remoteAddr); l {\n+ case header.IPv4AddressSize:\n+ netProto = header.IPv4ProtocolNumber\n+ case header.IPv6AddressSize:\n+ netProto = header.IPv6ProtocolNumber\n+ default:\n+ t.Fatalf(\"got unexpected address length = %d bytes\", l)\n+ }\n+\n+ if r, err := s.FindRoute(unspecifiedNICID, \"\" /* localAddr */, test.remoteAddr, netProto, false /* multicastLoop */); err != nil {\n+ t.Fatalf(\"FindRoute(%d, '', %s, %d): %s\", unspecifiedNICID, test.remoteAddr, netProto, err)\n+ } else if diff := cmp.Diff(r, test.expectedRoute, cmpopts.IgnoreUnexported(r)); diff != \"\" {\n+ t.Errorf(\"route mismatch (-want +got):\\n%s\", diff)\n+ }\n+ })\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -43,6 +43,9 @@ import (\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n+// Using header.IPv4AddressSize would cause an import cycle.\n+const ipv4AddressSize = 4\n+\n// Error represents an error in the netstack error space. Using a special type\n// ensures that errors outside of this space are not accidentally introduced.\n//\n@@ -320,6 +323,29 @@ func (s *Subnet) Broadcast() Address {\nreturn Address(addr)\n}\n+// IsBroadcast returns true if the address is considered a broadcast address.\n+func (s *Subnet) IsBroadcast(address Address) bool {\n+ // Only IPv4 supports the notion of a broadcast address.\n+ if len(address) != ipv4AddressSize {\n+ return false\n+ }\n+\n+ // Normally, we would just compare address with the subnet's broadcast\n+ // address but there is an exception where a simple comparison is not\n+ // correct. This exception is for /31 and /32 IPv4 subnets where all\n+ // addresses are considered valid host addresses.\n+ //\n+ // For /31 subnets, the case is easy. RFC 3021 Section 2.1 states that\n+ // both addresses in a /31 subnet \"MUST be interpreted as host addresses.\"\n+ //\n+ // For /32, the case is a bit more vague. RFC 3021 makes no mention of /32\n+ // subnets. However, the same reasoning applies - if an exception is not\n+ // made, then there do not exist any host addresses in a /32 subnet. RFC\n+ // 4632 Section 3.1 also vaguely implies this interpretation by referring\n+ // to addresses in /32 subnets as \"host routes.\"\n+ return s.Prefix() <= 30 && s.Broadcast() == address\n+}\n+\n// Equal returns true if s equals o.\n//\n// Needed to use cmp.Equal on Subnet as its fields are unexported.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -483,10 +483,6 @@ func (e *endpoint) write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, <-c\nnicID = e.BindNICID\n}\n- if to.Addr == header.IPv4Broadcast && !e.broadcast {\n- return 0, nil, tcpip.ErrBroadcastDisabled\n- }\n-\ndst, netProto, err := e.checkV4MappedLocked(*to)\nif err != nil {\nreturn 0, nil, err\n@@ -503,6 +499,10 @@ func (e *endpoint) write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, <-c\nresolve = route.Resolve\n}\n+ if !e.broadcast && route.IsBroadcast() {\n+ return 0, nil, tcpip.ErrBroadcastDisabled\n+ }\n+\nif route.IsResolutionRequired() {\nif ch, err := resolve(nil); err != nil {\nif err == tcpip.ErrWouldBlock {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/udp_test.go",
"new_path": "pkg/tcpip/transport/udp/udp_test.go",
"diff": "@@ -2142,3 +2142,192 @@ func (c *testContext) checkEndpointReadStats(incr uint64, want tcpip.TransportEn\nc.t.Errorf(\"Endpoint stats not matching for error %s got %+v want %+v\", err, got, want)\n}\n}\n+\n+func TestOutgoingSubnetBroadcast(t *testing.T) {\n+ const nicID1 = 1\n+\n+ ipv4Addr := tcpip.AddressWithPrefix{\n+ Address: \"\\xc0\\xa8\\x01\\x3a\",\n+ PrefixLen: 24,\n+ }\n+ ipv4Subnet := ipv4Addr.Subnet()\n+ ipv4SubnetBcast := ipv4Subnet.Broadcast()\n+ ipv4Gateway := tcpip.Address(\"\\xc0\\xa8\\x01\\x01\")\n+ ipv4AddrPrefix31 := tcpip.AddressWithPrefix{\n+ Address: \"\\xc0\\xa8\\x01\\x3a\",\n+ PrefixLen: 31,\n+ }\n+ ipv4Subnet31 := ipv4AddrPrefix31.Subnet()\n+ ipv4Subnet31Bcast := ipv4Subnet31.Broadcast()\n+ ipv4AddrPrefix32 := tcpip.AddressWithPrefix{\n+ Address: \"\\xc0\\xa8\\x01\\x3a\",\n+ PrefixLen: 32,\n+ }\n+ ipv4Subnet32 := ipv4AddrPrefix32.Subnet()\n+ ipv4Subnet32Bcast := ipv4Subnet32.Broadcast()\n+ ipv6Addr := tcpip.AddressWithPrefix{\n+ Address: \"\\x20\\x0a\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\",\n+ PrefixLen: 64,\n+ }\n+ ipv6Subnet := ipv6Addr.Subnet()\n+ ipv6SubnetBcast := ipv6Subnet.Broadcast()\n+ remNetAddr := tcpip.AddressWithPrefix{\n+ Address: \"\\x64\\x0a\\x7b\\x18\",\n+ PrefixLen: 24,\n+ }\n+ remNetSubnet := remNetAddr.Subnet()\n+ remNetSubnetBcast := remNetSubnet.Broadcast()\n+\n+ tests := []struct {\n+ name string\n+ nicAddr tcpip.ProtocolAddress\n+ routes []tcpip.Route\n+ remoteAddr tcpip.Address\n+ requiresBroadcastOpt bool\n+ }{\n+ {\n+ name: \"IPv4 Broadcast to local subnet\",\n+ nicAddr: tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: ipv4Addr,\n+ },\n+ routes: []tcpip.Route{\n+ {\n+ Destination: ipv4Subnet,\n+ NIC: nicID1,\n+ },\n+ },\n+ remoteAddr: ipv4SubnetBcast,\n+ requiresBroadcastOpt: true,\n+ },\n+ {\n+ name: \"IPv4 Broadcast to local /31 subnet\",\n+ nicAddr: tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: ipv4AddrPrefix31,\n+ },\n+ routes: []tcpip.Route{\n+ {\n+ Destination: ipv4Subnet31,\n+ NIC: nicID1,\n+ },\n+ },\n+ remoteAddr: ipv4Subnet31Bcast,\n+ requiresBroadcastOpt: false,\n+ },\n+ {\n+ name: \"IPv4 Broadcast to local /32 subnet\",\n+ nicAddr: tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: ipv4AddrPrefix32,\n+ },\n+ routes: []tcpip.Route{\n+ {\n+ Destination: ipv4Subnet32,\n+ NIC: nicID1,\n+ },\n+ },\n+ remoteAddr: ipv4Subnet32Bcast,\n+ requiresBroadcastOpt: false,\n+ },\n+ // IPv6 has no notion of a broadcast.\n+ {\n+ name: \"IPv6 'Broadcast' to local subnet\",\n+ nicAddr: tcpip.ProtocolAddress{\n+ Protocol: header.IPv6ProtocolNumber,\n+ AddressWithPrefix: ipv6Addr,\n+ },\n+ routes: []tcpip.Route{\n+ {\n+ Destination: ipv6Subnet,\n+ NIC: nicID1,\n+ },\n+ },\n+ remoteAddr: ipv6SubnetBcast,\n+ requiresBroadcastOpt: false,\n+ },\n+ {\n+ name: \"IPv4 Broadcast to remote subnet\",\n+ nicAddr: tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: ipv4Addr,\n+ },\n+ routes: []tcpip.Route{\n+ {\n+ Destination: remNetSubnet,\n+ Gateway: ipv4Gateway,\n+ NIC: nicID1,\n+ },\n+ },\n+ remoteAddr: remNetSubnetBcast,\n+ requiresBroadcastOpt: true,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{ipv4.NewProtocol(), ipv6.NewProtocol()},\n+\n+ TransportProtocols: []stack.TransportProtocol{udp.NewProtocol()},\n+ })\n+ e := channel.New(0, defaultMTU, \"\")\n+ if err := s.CreateNIC(nicID1, e); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID1, err)\n+ }\n+ if err := s.AddProtocolAddress(nicID1, test.nicAddr); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %+v): %s\", nicID1, test.nicAddr, err)\n+ }\n+\n+ s.SetRouteTable(test.routes)\n+\n+ var netProto tcpip.NetworkProtocolNumber\n+ switch l := len(test.remoteAddr); l {\n+ case header.IPv4AddressSize:\n+ netProto = header.IPv4ProtocolNumber\n+ case header.IPv6AddressSize:\n+ netProto = header.IPv6ProtocolNumber\n+ default:\n+ t.Fatalf(\"got unexpected address length = %d bytes\", l)\n+ }\n+\n+ wq := waiter.Queue{}\n+ ep, err := s.NewEndpoint(udp.ProtocolNumber, netProto, &wq)\n+ if err != nil {\n+ t.Fatalf(\"NewEndpoint(%d, %d, _): %s\", udp.ProtocolNumber, netProto, err)\n+ }\n+ defer ep.Close()\n+\n+ data := tcpip.SlicePayload([]byte{1, 2, 3, 4})\n+ to := tcpip.FullAddress{\n+ Addr: test.remoteAddr,\n+ Port: 80,\n+ }\n+ opts := tcpip.WriteOptions{To: &to}\n+ expectedErrWithoutBcastOpt := tcpip.ErrBroadcastDisabled\n+ if !test.requiresBroadcastOpt {\n+ expectedErrWithoutBcastOpt = nil\n+ }\n+\n+ if n, _, err := ep.Write(data, opts); err != expectedErrWithoutBcastOpt {\n+ t.Fatalf(\"got ep.Write(_, _) = (%d, _, %v), want = (_, _, %v)\", n, err, expectedErrWithoutBcastOpt)\n+ }\n+\n+ if err := ep.SetSockOptBool(tcpip.BroadcastOption, true); err != nil {\n+ t.Fatalf(\"got SetSockOptBool(BroadcastOption, true): %s\", err)\n+ }\n+\n+ if n, _, err := ep.Write(data, opts); err != nil {\n+ t.Fatalf(\"got ep.Write(_, _) = (%d, _, %s), want = (_, _, nil)\", n, err)\n+ }\n+\n+ if err := ep.SetSockOptBool(tcpip.BroadcastOption, false); err != nil {\n+ t.Fatalf(\"got SetSockOptBool(BroadcastOption, false): %s\", err)\n+ }\n+\n+ if n, _, err := ep.Write(data, opts); err != expectedErrWithoutBcastOpt {\n+ t.Fatalf(\"got ep.Write(_, _) = (%d, _, %v), want = (_, _, %v)\", n, err, expectedErrWithoutBcastOpt)\n+ }\n+ })\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use brodcast MAC for broadcast IPv4 packets
When sending packets to a known network's broadcast address, use the
broadcast MAC address.
Test:
- stack_test.TestOutgoingSubnetBroadcast
- udp_test.TestOutgoingSubnetBroadcast
PiperOrigin-RevId: 324062407 |
259,975 | 30.07.2020 13:31:05 | 25,200 | 78f1a18ab31fdc15155dd83d3ca96129b5031711 | Add runsc build benchmark. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/runsc/Dockerfile",
"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+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": "@@ -24,7 +24,18 @@ import (\n)\n// Note: CleanCache versions of this test require running with root permissions.\n-func BenchmarkABSL(b *testing.B) {\n+func BenchmarkBuildABSL(b *testing.B) {\n+ runBuildBenchmark(b, \"benchmarks/absl\", \"/abseil-cpp\", \"absl/base/...\")\n+}\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+func runBuildBenchmark(b *testing.B, image, workdir, target string) {\n+ b.Helper()\n// Get a machine from the Harness on which to run.\nmachine, err := h.GetMachine()\nif err != nil {\n@@ -51,20 +62,18 @@ func BenchmarkABSL(b *testing.B) {\ncontainer := machine.GetContainer(ctx, b)\ndefer container.CleanUp(ctx)\n- workdir := \"/abseil-cpp\"\n-\n// Start a container and sleep by an order of b.N.\nif err := container.Spawn(ctx, dockerutil.RunOpts{\n- Image: \"benchmarks/absl\",\n+ Image: image,\n}, \"sleep\", fmt.Sprintf(\"%d\", 1000000)); err != nil {\nb.Fatalf(\"run failed with: %v\", err)\n}\n// If we are running on a tmpfs, copy to /tmp which is a tmpfs.\nif bm.tmpfs {\n- if _, err := container.Exec(ctx, dockerutil.ExecOpts{},\n- \"cp\", \"-r\", \"/abseil-cpp\", \"/tmp/.\"); err != nil {\n- b.Fatal(\"failed to copy directory: %v\", err)\n+ if out, err := container.Exec(ctx, dockerutil.ExecOpts{},\n+ \"cp\", \"-r\", workdir, \"/tmp/.\"); err != nil {\n+ b.Fatal(\"failed to copy directory: %v %s\", err, out)\n}\nworkdir = \"/tmp\" + workdir\n}\n@@ -86,7 +95,7 @@ func BenchmarkABSL(b *testing.B) {\ngot, err := container.Exec(ctx, dockerutil.ExecOpts{\nWorkDir: workdir,\n- }, \"bazel\", \"build\", \"-c\", \"opt\", \"absl/base/...\")\n+ }, \"bazel\", \"build\", \"-c\", \"opt\", target)\nif err != nil {\nb.Fatalf(\"build failed with: %v\", err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add runsc build benchmark.
PiperOrigin-RevId: 324071377 |
259,858 | 30.07.2020 14:09:06 | 25,200 | 877fac48643772d3549b32d50b6d5f560770beb3 | Allocate a pseudo-tty for exec.
Otherwise Ctrl-C will kill the 'docker exec' as opposed to killing
the bazel command being run inside the container. | [
{
"change_type": "MODIFY",
"old_path": "tools/bazel.mk",
"new_path": "tools/bazel.mk",
"diff": "@@ -48,7 +48,10 @@ FULL_DOCKER_RUN_OPTIONS += -v \"$(BAZEL_CACHE):$(BAZEL_CACHE)\"\nFULL_DOCKER_RUN_OPTIONS += -v \"$(GCLOUD_CONFIG):$(GCLOUD_CONFIG)\"\nFULL_DOCKER_RUN_OPTIONS += -v \"/tmp:/tmp\"\nFULL_DOCKER_EXEC_OPTIONS := --user $(UID):$(GID)\n-FULL_DOCKER_EXEC_OPTIONS += -i\n+FULL_DOCKER_EXEC_OPTIONS += --interactive\n+ifeq (true,$(shell [[ -t 0 ]] && echo true))\n+FULL_DOCKER_EXEC_OPTIONS += --tty\n+endif\n# Add docker passthrough options.\nifneq ($(DOCKER_PRIVILEGED),)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allocate a pseudo-tty for exec.
Otherwise Ctrl-C will kill the 'docker exec' as opposed to killing
the bazel command being run inside the container.
PiperOrigin-RevId: 324079339 |
259,885 | 30.07.2020 14:13:11 | 25,200 | 3c70b4c986a2a6bb9b26f96e88f7fee878f29326 | Implement overlayfs_stale_read for vfs2. | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/vfs.go",
"new_path": "runsc/boot/vfs.go",
"diff": "@@ -171,10 +171,19 @@ func (c *containerMounter) setupVFS2(ctx context.Context, conf *Config, procArgs\nfunc (c *containerMounter) createMountNamespaceVFS2(ctx context.Context, conf *Config, creds *auth.Credentials) (*vfs.MountNamespace, error) {\nfd := c.fds.remove()\n- opts := strings.Join(p9MountData(fd, conf.FileAccess, true /* vfs2 */), \",\")\n+ opts := p9MountData(fd, conf.FileAccess, true /* vfs2 */)\n+\n+ if conf.OverlayfsStaleRead {\n+ // We can't check for overlayfs here because sandbox is chroot'ed and gofer\n+ // can only send mount options for specs.Mounts (specs.Root is missing\n+ // Options field). So assume root is always on top of overlayfs.\n+ opts = append(opts, \"overlayfs_stale_read\")\n+ }\nlog.Infof(\"Mounting root over 9P, ioFD: %d\", fd)\n- mns, err := c.k.VFS().NewMountNamespace(ctx, creds, \"\", gofer.Name, &vfs.GetFilesystemOptions{Data: opts})\n+ mns, err := c.k.VFS().NewMountNamespace(ctx, creds, \"\", gofer.Name, &vfs.GetFilesystemOptions{\n+ Data: strings.Join(opts, \",\"),\n+ })\nif err != nil {\nreturn nil, fmt.Errorf(\"setting up mount namespace: %w\", err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/integration_test.go",
"new_path": "test/e2e/integration_test.go",
"diff": "@@ -431,11 +431,13 @@ func TestHostOverlayfsCopyUp(t *testing.T) {\nd := dockerutil.MakeContainer(ctx, t)\ndefer d.CleanUp(ctx)\n- if _, err := d.Run(ctx, dockerutil.RunOpts{\n+ if got, err := d.Run(ctx, dockerutil.RunOpts{\nImage: \"basic/hostoverlaytest\",\nWorkDir: \"/root\",\n}, \"./test\"); err != nil {\nt.Fatalf(\"docker run failed: %v\", err)\n+ } else if got != \"\" {\n+ t.Errorf(\"test failed:\\n%s\", got)\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement overlayfs_stale_read for vfs2.
PiperOrigin-RevId: 324080111 |
260,004 | 30.07.2020 14:19:38 | 25,200 | 9960a816a9ad65a4a6620eee5a66e5cc071b60cb | Enforce fragment block size and validate args
Allow configuring fragmentation.Fragmentation with a fragment
block size which will be enforced when processing fragments. Also
validate arguments when processing fragments.
Test:
- fragmentation.TestErrors
- ipv6_test.TestReceiveIPv6Fragments
- ipv4_test.TestReceiveIPv6Fragments | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/fragmentation/fragmentation.go",
"new_path": "pkg/tcpip/network/fragmentation/fragmentation.go",
"diff": "package fragmentation\nimport (\n+ \"errors\"\n\"fmt\"\n\"log\"\n\"time\"\n@@ -25,20 +26,31 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n)\n+const (\n// DefaultReassembleTimeout is based on the linux stack: net.ipv4.ipfrag_time.\n-const DefaultReassembleTimeout = 30 * time.Second\n+ DefaultReassembleTimeout = 30 * time.Second\n// HighFragThreshold is the threshold at which we start trimming old\n// fragmented packets. Linux uses a default value of 4 MB. See\n// net.ipv4.ipfrag_high_thresh for more information.\n-const HighFragThreshold = 4 << 20 // 4MB\n+ HighFragThreshold = 4 << 20 // 4MB\n// LowFragThreshold is the threshold we reach to when we start dropping\n// older fragmented packets. It's important that we keep enough room for newer\n// packets to be re-assembled. Hence, this needs to be lower than\n// HighFragThreshold enough. Linux uses a default value of 3 MB. See\n// net.ipv4.ipfrag_low_thresh for more information.\n-const LowFragThreshold = 3 << 20 // 3MB\n+ LowFragThreshold = 3 << 20 // 3MB\n+\n+ // minBlockSize is the minimum block size for fragments.\n+ minBlockSize = 1\n+)\n+\n+var (\n+ // ErrInvalidArgs indicates to the caller that that an invalid argument was\n+ // provided.\n+ ErrInvalidArgs = errors.New(\"invalid args\")\n+)\n// Fragmentation is the main structure that other modules\n// of the stack should use to implement IP Fragmentation.\n@@ -50,10 +62,13 @@ type Fragmentation struct {\nrList reassemblerList\nsize int\ntimeout time.Duration\n+ blockSize uint16\n}\n// NewFragmentation creates a new Fragmentation.\n//\n+// blockSize specifies the fragment block size, in bytes.\n+//\n// highMemoryLimit specifies the limit on the memory consumed\n// by the fragments stored by Fragmentation (overhead of internal data-structures\n// is not accounted). Fragments are dropped when the limit is reached.\n@@ -64,7 +79,7 @@ type Fragmentation struct {\n// reassemblingTimeout specifies the maximum time allowed to reassemble a packet.\n// Fragments are lazily evicted only when a new a packet with an\n// already existing fragmentation-id arrives after the timeout.\n-func NewFragmentation(highMemoryLimit, lowMemoryLimit int, reassemblingTimeout time.Duration) *Fragmentation {\n+func NewFragmentation(blockSize uint16, highMemoryLimit, lowMemoryLimit int, reassemblingTimeout time.Duration) *Fragmentation {\nif lowMemoryLimit >= highMemoryLimit {\nlowMemoryLimit = highMemoryLimit\n}\n@@ -73,17 +88,46 @@ func NewFragmentation(highMemoryLimit, lowMemoryLimit int, reassemblingTimeout t\nlowMemoryLimit = 0\n}\n+ if blockSize < minBlockSize {\n+ blockSize = minBlockSize\n+ }\n+\nreturn &Fragmentation{\nreassemblers: make(map[uint32]*reassembler),\nhighLimit: highMemoryLimit,\nlowLimit: lowMemoryLimit,\ntimeout: reassemblingTimeout,\n+ blockSize: blockSize,\n}\n}\n// Process processes an incoming fragment belonging to an ID and returns a\n// complete packet when all the packets belonging to that ID have been received.\n+//\n+// [first, last] is the range of the fragment bytes.\n+//\n+// first must be a multiple of the block size f is configured with. The size\n+// of the fragment data must be a multiple of the block size, unless there are\n+// no fragments following this fragment (more set to false).\nfunc (f *Fragmentation) Process(id uint32, first, last uint16, more bool, vv buffer.VectorisedView) (buffer.VectorisedView, bool, error) {\n+ if first > last {\n+ return buffer.VectorisedView{}, false, fmt.Errorf(\"first=%d is greater than last=%d: %w\", first, last, ErrInvalidArgs)\n+ }\n+\n+ if first%f.blockSize != 0 {\n+ return buffer.VectorisedView{}, false, fmt.Errorf(\"first=%d is not a multiple of block size=%d: %w\", first, f.blockSize, ErrInvalidArgs)\n+ }\n+\n+ fragmentSize := last - first + 1\n+ if more && fragmentSize%f.blockSize != 0 {\n+ return buffer.VectorisedView{}, false, fmt.Errorf(\"fragment size=%d bytes is not a multiple of block size=%d on non-final fragment: %w\", fragmentSize, f.blockSize, ErrInvalidArgs)\n+ }\n+\n+ if l := vv.Size(); l < int(fragmentSize) {\n+ return buffer.VectorisedView{}, false, fmt.Errorf(\"got fragment size=%d bytes less than the expected fragment size=%d bytes (first=%d last=%d): %w\", l, fragmentSize, first, last, ErrInvalidArgs)\n+ }\n+ vv.CapLength(int(fragmentSize))\n+\nf.mu.Lock()\nr, ok := f.reassemblers[id]\nif ok && r.tooOld(f.timeout) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/fragmentation/fragmentation_test.go",
"new_path": "pkg/tcpip/network/fragmentation/fragmentation_test.go",
"diff": "package fragmentation\nimport (\n+ \"errors\"\n\"reflect\"\n\"testing\"\n\"time\"\n@@ -81,7 +82,7 @@ var processTestCases = []struct {\nfunc TestFragmentationProcess(t *testing.T) {\nfor _, c := range processTestCases {\nt.Run(c.comment, func(t *testing.T) {\n- f := NewFragmentation(1024, 512, DefaultReassembleTimeout)\n+ f := NewFragmentation(minBlockSize, 1024, 512, DefaultReassembleTimeout)\nfor i, in := range c.in {\nvv, done, err := f.Process(in.id, in.first, in.last, in.more, in.vv)\nif err != nil {\n@@ -110,7 +111,7 @@ func TestFragmentationProcess(t *testing.T) {\nfunc TestReassemblingTimeout(t *testing.T) {\ntimeout := time.Millisecond\n- f := NewFragmentation(1024, 512, timeout)\n+ f := NewFragmentation(minBlockSize, 1024, 512, timeout)\n// Send first fragment with id = 0, first = 0, last = 0, and more = true.\nf.Process(0, 0, 0, true, vv(1, \"0\"))\n// Sleep more than the timeout.\n@@ -127,7 +128,7 @@ func TestReassemblingTimeout(t *testing.T) {\n}\nfunc TestMemoryLimits(t *testing.T) {\n- f := NewFragmentation(3, 1, DefaultReassembleTimeout)\n+ f := NewFragmentation(minBlockSize, 3, 1, DefaultReassembleTimeout)\n// Send first fragment with id = 0.\nf.Process(0, 0, 0, true, vv(1, \"0\"))\n// Send first fragment with id = 1.\n@@ -151,7 +152,7 @@ func TestMemoryLimits(t *testing.T) {\n}\nfunc TestMemoryLimitsIgnoresDuplicates(t *testing.T) {\n- f := NewFragmentation(1, 0, DefaultReassembleTimeout)\n+ f := NewFragmentation(minBlockSize, 1, 0, DefaultReassembleTimeout)\n// Send first fragment with id = 0.\nf.Process(0, 0, 0, true, vv(1, \"0\"))\n// Send the same packet again.\n@@ -163,3 +164,99 @@ func TestMemoryLimitsIgnoresDuplicates(t *testing.T) {\nt.Errorf(\"Wrong size, duplicates are not handled correctly: got=%d, want=%d.\", got, want)\n}\n}\n+\n+func TestErrors(t *testing.T) {\n+ const fragID = 5\n+\n+ tests := []struct {\n+ name string\n+ blockSize uint16\n+ first uint16\n+ last uint16\n+ more bool\n+ data string\n+ err error\n+ }{\n+ {\n+ name: \"exact block size without more\",\n+ blockSize: 2,\n+ first: 2,\n+ last: 3,\n+ more: false,\n+ data: \"01\",\n+ },\n+ {\n+ name: \"exact block size with more\",\n+ blockSize: 2,\n+ first: 2,\n+ last: 3,\n+ more: true,\n+ data: \"01\",\n+ },\n+ {\n+ name: \"exact block size with more and extra data\",\n+ blockSize: 2,\n+ first: 2,\n+ last: 3,\n+ more: true,\n+ data: \"012\",\n+ },\n+ {\n+ name: \"exact block size with more and too little data\",\n+ blockSize: 2,\n+ first: 2,\n+ last: 3,\n+ more: true,\n+ data: \"0\",\n+ err: ErrInvalidArgs,\n+ },\n+ {\n+ name: \"not exact block size with more\",\n+ blockSize: 2,\n+ first: 2,\n+ last: 2,\n+ more: true,\n+ data: \"0\",\n+ err: ErrInvalidArgs,\n+ },\n+ {\n+ name: \"not exact block size without more\",\n+ blockSize: 2,\n+ first: 2,\n+ last: 2,\n+ more: false,\n+ data: \"0\",\n+ },\n+ {\n+ name: \"first not a multiple of block size\",\n+ blockSize: 2,\n+ first: 3,\n+ last: 4,\n+ more: true,\n+ data: \"01\",\n+ err: ErrInvalidArgs,\n+ },\n+ {\n+ name: \"first more than last\",\n+ blockSize: 2,\n+ first: 4,\n+ last: 3,\n+ more: true,\n+ data: \"01\",\n+ err: ErrInvalidArgs,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ f := NewFragmentation(test.blockSize, HighFragThreshold, LowFragThreshold, DefaultReassembleTimeout)\n+ _, done, err := f.Process(fragID, test.first, test.last, test.more, vv(len(test.data), test.data))\n+ if !errors.Is(err, test.err) {\n+ t.Errorf(\"got Proceess(%d, %d, %d, %t, %q) = (_, _, %v), want = (_, _, %v)\", fragID, test.first, test.last, test.more, test.data, err, test.err)\n+ }\n+ if done {\n+ t.Errorf(\"got Proceess(%d, %d, %d, %t, %q) = (_, true, _), want = (_, false, _)\", fragID, test.first, test.last, test.more, test.data)\n+ }\n+ })\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -45,6 +45,10 @@ const (\n// buckets is the number of identifier buckets.\nbuckets = 2048\n+\n+ // The size of a fragment block, in bytes, as per RFC 791 section 3.1,\n+ // page 14.\n+ fragmentblockSize = 8\n)\ntype endpoint struct {\n@@ -66,7 +70,7 @@ func (p *protocol) NewEndpoint(nicID tcpip.NICID, addrWithPrefix tcpip.AddressWi\nprefixLen: addrWithPrefix.PrefixLen,\nlinkEP: linkEP,\ndispatcher: dispatcher,\n- fragmentation: fragmentation.NewFragmentation(fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, fragmentation.DefaultReassembleTimeout),\n+ fragmentation: fragmentation.NewFragmentation(fragmentblockSize, fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, fragmentation.DefaultReassembleTimeout),\nprotocol: p,\nstack: st,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"diff": "@@ -519,6 +519,11 @@ func TestReceiveFragments(t *testing.T) {\n// UDP header plus a payload of 0..256 in increments of 2.\nipv4Payload2 := udpGen(128, 2)\nudpPayload2 := ipv4Payload2[header.UDPMinimumSize:]\n+ // UDP header plus a payload of 0..256 in increments of 3.\n+ // Used to test cases where the fragment blocks are not a multiple of\n+ // the fragment block size of 8 (RFC 791 section 3.1 page 14).\n+ ipv4Payload3 := udpGen(127, 3)\n+ udpPayload3 := ipv4Payload3[header.UDPMinimumSize:]\ntype fragmentData struct {\nid uint16\n@@ -544,6 +549,18 @@ func TestReceiveFragments(t *testing.T) {\n},\nexpectedPayloads: [][]byte{udpPayload1},\n},\n+ {\n+ name: \"No fragmentation with size not a multiple of fragment block size\",\n+ fragments: []fragmentData{\n+ {\n+ id: 1,\n+ flags: 0,\n+ fragmentOffset: 0,\n+ payload: ipv4Payload3,\n+ },\n+ },\n+ expectedPayloads: [][]byte{udpPayload3},\n+ },\n{\nname: \"More fragments without payload\",\nfragments: []fragmentData{\n@@ -586,6 +603,42 @@ func TestReceiveFragments(t *testing.T) {\n},\nexpectedPayloads: [][]byte{udpPayload1},\n},\n+ {\n+ name: \"Two fragments with last fragment size not a multiple of fragment block size\",\n+ fragments: []fragmentData{\n+ {\n+ id: 1,\n+ flags: header.IPv4FlagMoreFragments,\n+ fragmentOffset: 0,\n+ payload: ipv4Payload3[:64],\n+ },\n+ {\n+ id: 1,\n+ flags: 0,\n+ fragmentOffset: 64,\n+ payload: ipv4Payload3[64:],\n+ },\n+ },\n+ expectedPayloads: [][]byte{udpPayload3},\n+ },\n+ {\n+ name: \"Two fragments with first fragment size not a multiple of fragment block size\",\n+ fragments: []fragmentData{\n+ {\n+ id: 1,\n+ flags: header.IPv4FlagMoreFragments,\n+ fragmentOffset: 0,\n+ payload: ipv4Payload3[:63],\n+ },\n+ {\n+ id: 1,\n+ flags: 0,\n+ fragmentOffset: 63,\n+ payload: ipv4Payload3[63:],\n+ },\n+ },\n+ expectedPayloads: nil,\n+ },\n{\nname: \"Second fragment has MoreFlags set\",\nfragments: []fragmentData{\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -467,7 +467,7 @@ func (p *protocol) NewEndpoint(nicID tcpip.NICID, addrWithPrefix tcpip.AddressWi\nlinkEP: linkEP,\nlinkAddrCache: linkAddrCache,\ndispatcher: dispatcher,\n- fragmentation: fragmentation.NewFragmentation(fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, fragmentation.DefaultReassembleTimeout),\n+ fragmentation: fragmentation.NewFragmentation(header.IPv6FragmentExtHdrFragmentOffsetBytesPerUnit, fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, fragmentation.DefaultReassembleTimeout),\nprotocol: p,\n}, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6_test.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6_test.go",
"diff": "@@ -678,13 +678,18 @@ type fragmentData struct {\n}\nfunc TestReceiveIPv6Fragments(t *testing.T) {\n- const nicID = 1\n- const udpPayload1Length = 256\n- const udpPayload2Length = 128\n- const fragmentExtHdrLen = 8\n+ const (\n+ nicID = 1\n+ udpPayload1Length = 256\n+ udpPayload2Length = 128\n+ // Used to test cases where the fragment blocks are not a multiple of\n+ // the fragment block size of 8 (RFC 8200 section 4.5).\n+ udpPayload3Length = 127\n+ fragmentExtHdrLen = 8\n// Note, not all routing extension headers will be 8 bytes but this test\n// uses 8 byte routing extension headers for most sub tests.\n- const routingExtHdrLen = 8\n+ routingExtHdrLen = 8\n+ )\nudpGen := func(payload []byte, multiplier uint8) buffer.View {\npayloadLen := len(payload)\n@@ -716,6 +721,10 @@ func TestReceiveIPv6Fragments(t *testing.T) {\nudpPayload2 := udpPayload2Buf[:]\nipv6Payload2 := udpGen(udpPayload2, 2)\n+ var udpPayload3Buf [udpPayload3Length]byte\n+ udpPayload3 := udpPayload3Buf[:]\n+ ipv6Payload3 := udpGen(udpPayload3, 3)\n+\ntests := []struct {\nname string\nexpectedPayload []byte\n@@ -750,6 +759,24 @@ func TestReceiveIPv6Fragments(t *testing.T) {\n},\nexpectedPayloads: [][]byte{udpPayload1},\n},\n+ {\n+ name: \"Atomic fragment with size not a multiple of fragment block size\",\n+ fragments: []fragmentData{\n+ {\n+ nextHdr: fragmentExtHdrID,\n+ data: buffer.NewVectorisedView(\n+ fragmentExtHdrLen+len(ipv6Payload3),\n+ []buffer.View{\n+ // Fragment extension header.\n+ buffer.View([]byte{uint8(header.UDPProtocolNumber), 0, 0, 0, 0, 0, 0, 0}),\n+\n+ ipv6Payload3,\n+ },\n+ ),\n+ },\n+ },\n+ expectedPayloads: [][]byte{udpPayload3},\n+ },\n{\nname: \"Two fragments\",\nfragments: []fragmentData{\n@@ -784,6 +811,74 @@ func TestReceiveIPv6Fragments(t *testing.T) {\n},\nexpectedPayloads: [][]byte{udpPayload1},\n},\n+ {\n+ name: \"Two fragments with last fragment size not a multiple of fragment block size\",\n+ fragments: []fragmentData{\n+ {\n+ nextHdr: fragmentExtHdrID,\n+ data: buffer.NewVectorisedView(\n+ fragmentExtHdrLen+64,\n+ []buffer.View{\n+ // Fragment extension header.\n+ //\n+ // Fragment offset = 0, More = true, ID = 1\n+ buffer.View([]byte{uint8(header.UDPProtocolNumber), 0, 0, 1, 0, 0, 0, 1}),\n+\n+ ipv6Payload3[:64],\n+ },\n+ ),\n+ },\n+ {\n+ nextHdr: fragmentExtHdrID,\n+ data: buffer.NewVectorisedView(\n+ fragmentExtHdrLen+len(ipv6Payload3)-64,\n+ []buffer.View{\n+ // Fragment extension header.\n+ //\n+ // Fragment offset = 8, More = false, ID = 1\n+ buffer.View([]byte{uint8(header.UDPProtocolNumber), 0, 0, 64, 0, 0, 0, 1}),\n+\n+ ipv6Payload3[64:],\n+ },\n+ ),\n+ },\n+ },\n+ expectedPayloads: [][]byte{udpPayload3},\n+ },\n+ {\n+ name: \"Two fragments with first fragment size not a multiple of fragment block size\",\n+ fragments: []fragmentData{\n+ {\n+ nextHdr: fragmentExtHdrID,\n+ data: buffer.NewVectorisedView(\n+ fragmentExtHdrLen+63,\n+ []buffer.View{\n+ // Fragment extension header.\n+ //\n+ // Fragment offset = 0, More = true, ID = 1\n+ buffer.View([]byte{uint8(header.UDPProtocolNumber), 0, 0, 1, 0, 0, 0, 1}),\n+\n+ ipv6Payload3[:63],\n+ },\n+ ),\n+ },\n+ {\n+ nextHdr: fragmentExtHdrID,\n+ data: buffer.NewVectorisedView(\n+ fragmentExtHdrLen+len(ipv6Payload3)-63,\n+ []buffer.View{\n+ // Fragment extension header.\n+ //\n+ // Fragment offset = 8, More = false, ID = 1\n+ buffer.View([]byte{uint8(header.UDPProtocolNumber), 0, 0, 64, 0, 0, 0, 1}),\n+\n+ ipv6Payload3[63:],\n+ },\n+ ),\n+ },\n+ },\n+ expectedPayloads: nil,\n+ },\n{\nname: \"Two fragments with different IDs\",\nfragments: []fragmentData{\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enforce fragment block size and validate args
Allow configuring fragmentation.Fragmentation with a fragment
block size which will be enforced when processing fragments. Also
validate arguments when processing fragments.
Test:
- fragmentation.TestErrors
- ipv6_test.TestReceiveIPv6Fragments
- ipv4_test.TestReceiveIPv6Fragments
PiperOrigin-RevId: 324081521 |
260,023 | 30.07.2020 22:47:37 | 25,200 | ad8164bb50dd01bfd59c9a6c72d9cbb0d4710f15 | Fix TCP CurrentConnected counter updates.
CurrentConnected counter is incorrectly decremented on close of an
endpoint which is still not connected.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -1024,14 +1024,19 @@ func (e *endpoint) transitionToStateEstablishedLocked(h *handshake) {\n// delivered to this endpoint from the demuxer when the endpoint\n// is transitioned to StateClose.\nfunc (e *endpoint) transitionToStateCloseLocked() {\n- if e.EndpointState() == StateClose {\n+ s := e.EndpointState()\n+ if s == StateClose {\nreturn\n}\n+\n+ if s.connected() {\n+ e.stack.Stats().TCP.CurrentConnected.Decrement()\n+ e.stack.Stats().TCP.EstablishedClosed.Increment()\n+ }\n+\n// Mark the endpoint as fully closed for reads/writes.\ne.cleanupLocked()\ne.setEndpointState(StateClose)\n- e.stack.Stats().TCP.CurrentConnected.Decrement()\n- e.stack.Stats().TCP.EstablishedClosed.Increment()\n}\n// tryDeliverSegmentFromClosedEndpoint attempts to deliver the parsed\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"new_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"diff": "@@ -146,6 +146,24 @@ func TestActiveFailedConnectionAttemptIncrement(t *testing.T) {\n}\n}\n+func TestCloseWithoutConnect(t *testing.T) {\n+ c := context.New(t, defaultMTU)\n+ defer c.Cleanup()\n+\n+ // Create TCP endpoint.\n+ var err *tcpip.Error\n+ c.EP, err = c.Stack().NewEndpoint(tcp.ProtocolNumber, ipv4.ProtocolNumber, &c.WQ)\n+ if err != nil {\n+ t.Fatalf(\"NewEndpoint failed: %s\", err)\n+ }\n+\n+ c.EP.Close()\n+\n+ if got := c.Stack().Stats().TCP.CurrentConnected.Value(); got != 0 {\n+ t.Errorf(\"got stats.TCP.CurrentConnected.Value() = %d, want = 0\", got)\n+ }\n+}\n+\nfunc TestTCPSegmentsSentIncrement(t *testing.T) {\nc := context.New(t, defaultMTU)\ndefer c.Cleanup()\n@@ -1276,7 +1294,15 @@ func TestConnectBindToDevice(t *testing.T) {\n}\n}\n-func TestRstOnSynSent(t *testing.T) {\n+func TestSynSent(t *testing.T) {\n+ for _, test := range []struct {\n+ name string\n+ reset bool\n+ }{\n+ {\"RstOnSynSent\", true},\n+ {\"CloseOnSynSent\", false},\n+ } {\n+ t.Run(test.name, func(t *testing.T) {\nc := context.New(t, defaultMTU)\ndefer c.Cleanup()\n@@ -1303,15 +1329,15 @@ func TestRstOnSynSent(t *testing.T) {\n),\n)\n- // Ensure that we've reached SynSent state\nif got, want := tcp.EndpointState(c.EP.State()), tcp.StateSynSent; got != want {\nt.Fatalf(\"got State() = %s, want %s\", got, want)\n}\ntcpHdr := header.TCP(header.IPv4(b).Payload())\nc.IRS = seqnum.Value(tcpHdr.SequenceNumber())\n+ if test.reset {\n// Send a packet with a proper ACK and a RST flag to cause the socket\n- // to Error and close out\n+ // to error and close out.\niss := seqnum.Value(789)\nrcvWnd := seqnum.Size(30000)\nc.SendPacket(nil, &context.Headers{\n@@ -1323,6 +1349,9 @@ func TestRstOnSynSent(t *testing.T) {\nRcvWnd: rcvWnd,\nTCPOpts: nil,\n})\n+ } else {\n+ c.EP.Close()\n+ }\n// Wait for receive to be notified.\nselect {\n@@ -1331,14 +1360,26 @@ func TestRstOnSynSent(t *testing.T) {\nt.Fatal(\"timed out waiting for packet to arrive\")\n}\n+ if test.reset {\nif _, _, err := c.EP.Read(nil); err != tcpip.ErrConnectionRefused {\nt.Fatalf(\"got c.EP.Read(nil) = %s, want = %s\", err, tcpip.ErrConnectionRefused)\n}\n+ } else {\n+ if _, _, err := c.EP.Read(nil); err != tcpip.ErrAborted {\n+ t.Fatalf(\"got c.EP.Read(nil) = %s, want = %s\", err, tcpip.ErrAborted)\n+ }\n+ }\n+\n+ if got := c.Stack().Stats().TCP.CurrentConnected.Value(); got != 0 {\n+ t.Errorf(\"got stats.TCP.CurrentConnected.Value() = %d, want = 0\", got)\n+ }\n// Due to the RST the endpoint should be in an error state.\nif got, want := tcp.EndpointState(c.EP.State()), tcp.StateError; got != want {\nt.Fatalf(\"got State() = %s, want %s\", got, want)\n}\n+ })\n+ }\n}\nfunc TestOutOfOrderReceive(t *testing.T) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix TCP CurrentConnected counter updates.
CurrentConnected counter is incorrectly decremented on close of an
endpoint which is still not connected.
Fixes #3443
PiperOrigin-RevId: 324155171 |
259,860 | 31.07.2020 00:38:57 | 25,200 | 68a7da9549ac4f6290fe85d2dab550e11f16b209 | Clean up vfs2 fallocate.
Move to setstat.go and add a FileDescription wrapper method. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/filesystem.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/filesystem.go",
"diff": "@@ -18,7 +18,6 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n- \"gvisor.dev/gvisor/pkg/sentry/limits\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n@@ -245,55 +244,6 @@ func renameat(t *kernel.Task, olddirfd int32, oldpathAddr usermem.Addr, newdirfd\n})\n}\n-// Fallocate implements linux system call fallocate(2).\n-func Fallocate(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n- fd := args[0].Int()\n- mode := args[1].Uint64()\n- offset := args[2].Int64()\n- length := args[3].Int64()\n-\n- file := t.GetFileVFS2(fd)\n-\n- if file == nil {\n- return 0, nil, syserror.EBADF\n- }\n- defer file.DecRef()\n-\n- if !file.IsWritable() {\n- return 0, nil, syserror.EBADF\n- }\n-\n- if mode != 0 {\n- return 0, nil, syserror.ENOTSUP\n- }\n-\n- if offset < 0 || length <= 0 {\n- return 0, nil, syserror.EINVAL\n- }\n-\n- size := offset + length\n-\n- if size < 0 {\n- return 0, nil, syserror.EFBIG\n- }\n-\n- limit := limits.FromContext(t).Get(limits.FileSize).Cur\n-\n- if uint64(size) >= limit {\n- t.SendSignal(&arch.SignalInfo{\n- Signo: int32(linux.SIGXFSZ),\n- Code: arch.SignalInfoUser,\n- })\n- return 0, nil, syserror.EFBIG\n- }\n-\n- return 0, nil, file.Impl().Allocate(t, mode, uint64(offset), uint64(length))\n-\n- // File length modified, generate notification.\n- // TODO(gvisor.dev/issue/1479): Reenable when Inotify is ported.\n- // file.Dirent.InotifyEvent(linux.IN_MODIFY, 0)\n-}\n-\n// Rmdir implements Linux syscall rmdir(2).\nfunc Rmdir(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\npathAddr := args[0].Pointer()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/setstat.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/setstat.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/limits\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n@@ -211,6 +212,55 @@ func Ftruncate(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sys\nreturn 0, nil, handleSetSizeError(t, err)\n}\n+// Fallocate implements linux system call fallocate(2).\n+func Fallocate(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ fd := args[0].Int()\n+ mode := args[1].Uint64()\n+ offset := args[2].Int64()\n+ length := args[3].Int64()\n+\n+ file := t.GetFileVFS2(fd)\n+\n+ if file == nil {\n+ return 0, nil, syserror.EBADF\n+ }\n+ defer file.DecRef()\n+\n+ if !file.IsWritable() {\n+ return 0, nil, syserror.EBADF\n+ }\n+\n+ if mode != 0 {\n+ return 0, nil, syserror.ENOTSUP\n+ }\n+\n+ if offset < 0 || length <= 0 {\n+ return 0, nil, syserror.EINVAL\n+ }\n+\n+ size := offset + length\n+\n+ if size < 0 {\n+ return 0, nil, syserror.EFBIG\n+ }\n+\n+ limit := limits.FromContext(t).Get(limits.FileSize).Cur\n+\n+ if uint64(size) >= limit {\n+ t.SendSignal(&arch.SignalInfo{\n+ Signo: int32(linux.SIGXFSZ),\n+ Code: arch.SignalInfoUser,\n+ })\n+ return 0, nil, syserror.EFBIG\n+ }\n+\n+ return 0, nil, file.Allocate(t, mode, uint64(offset), uint64(length))\n+\n+ // File length modified, generate notification.\n+ // TODO(gvisor.dev/issue/1479): Reenable when Inotify is ported.\n+ // file.Dirent.InotifyEvent(linux.IN_MODIFY, 0)\n+}\n+\n// Utime implements Linux syscall utime(2).\nfunc Utime(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\npathAddr := args[0].Pointer()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/file_description.go",
"new_path": "pkg/sentry/vfs/file_description.go",
"diff": "@@ -354,7 +354,7 @@ type FileDescriptionImpl interface {\n// represented by the FileDescription.\nStatFS(ctx context.Context) (linux.Statfs, error)\n- // Allocate grows file represented by FileDescription to offset + length bytes.\n+ // Allocate grows the file to offset + length bytes.\n// Only mode == 0 is supported currently.\nAllocate(ctx context.Context, mode, offset, length uint64) error\n@@ -563,6 +563,11 @@ func (fd *FileDescription) StatFS(ctx context.Context) (linux.Statfs, error) {\nreturn fd.impl.StatFS(ctx)\n}\n+// Allocate grows file represented by FileDescription to offset + length bytes.\n+func (fd *FileDescription) Allocate(ctx context.Context, mode, offset, length uint64) error {\n+ return fd.impl.Allocate(ctx, mode, offset, length)\n+}\n+\n// Readiness implements waiter.Waitable.Readiness.\n//\n// It returns fd's I/O readiness.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Clean up vfs2 fallocate.
Move to setstat.go and add a FileDescription wrapper method.
PiperOrigin-RevId: 324165277 |
259,891 | 11.06.2020 20:33:56 | 25,200 | 2a7b2a61e3ea32129c26eeaa6fab3d81a5d8ad6e | iptables: support SO_ORIGINAL_DST
Envoy uses this to get the original destination of redirected
packets. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/netfilter.go",
"new_path": "pkg/abi/linux/netfilter.go",
"diff": "@@ -59,7 +59,7 @@ var VerdictStrings = map[int32]string{\nNF_RETURN: \"RETURN\",\n}\n-// Socket options. These correspond to values in\n+// Socket options for SOL_SOCKET. These correspond to values in\n// include/uapi/linux/netfilter_ipv4/ip_tables.h.\nconst (\nIPT_BASE_CTL = 64\n@@ -74,6 +74,12 @@ const (\nIPT_SO_GET_MAX = IPT_SO_GET_REVISION_TARGET\n)\n+// Socket option for SOL_IP. This corresponds to the value in\n+// include/uapi/linux/netfilter_ipv4.h.\n+const (\n+ SO_ORIGINAL_DST = 80\n+)\n+\n// Name lengths. These correspond to values in\n// include/uapi/linux/netfilter/x_tables.h.\nconst (\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/socket.go",
"new_path": "pkg/abi/linux/socket.go",
"diff": "@@ -239,11 +239,13 @@ const SockAddrMax = 128\ntype InetAddr [4]byte\n// SockAddrInet is struct sockaddr_in, from uapi/linux/in.h.\n+//\n+// +marshal\ntype SockAddrInet struct {\nFamily uint16\nPort uint16\nAddr InetAddr\n- Zero [8]uint8 // pad to sizeof(struct sockaddr).\n+ _ [8]uint8 // pad to sizeof(struct sockaddr).\n}\n// InetMulticastRequest is struct ip_mreq, from uapi/linux/in.h.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -1490,6 +1490,10 @@ func getSockOptIPv6(t *kernel.Task, ep commonEndpoint, name, outLen int) (marsha\nvP := primitive.Int32(boolToInt32(v))\nreturn &vP, nil\n+ case linux.SO_ORIGINAL_DST:\n+ // TODO(gvisor.dev/issue/170): ip6tables.\n+ return nil, syserr.ErrInvalidArgument\n+\ndefault:\nemitUnimplementedEventIPv6(t, name)\n}\n@@ -1600,6 +1604,19 @@ func getSockOptIP(t *kernel.Task, ep commonEndpoint, name, outLen int, family in\nvP := primitive.Int32(boolToInt32(v))\nreturn &vP, nil\n+ case linux.SO_ORIGINAL_DST:\n+ if outLen < int(binary.Size(linux.SockAddrInet{})) {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ var v tcpip.OriginalDestinationOption\n+ if err := ep.GetSockOpt(&v); err != nil {\n+ return nil, syserr.TranslateNetstackError(err)\n+ }\n+\n+ a, _ := ConvertAddress(linux.AF_INET, tcpip.FullAddress(v))\n+ return a.(*linux.SockAddrInet), nil\n+\ndefault:\nemitUnimplementedEventIP(t, name)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/socket.go",
"new_path": "pkg/sentry/strace/socket.go",
"diff": "@@ -521,6 +521,7 @@ var sockOptNames = map[uint64]abi.ValueSet{\nlinux.IP_ROUTER_ALERT: \"IP_ROUTER_ALERT\",\nlinux.IP_PKTOPTIONS: \"IP_PKTOPTIONS\",\nlinux.IP_MTU: \"IP_MTU\",\n+ linux.SO_ORIGINAL_DST: \"SO_ORIGINAL_DST\",\n},\nlinux.SOL_SOCKET: {\nlinux.SO_ERROR: \"SO_ERROR\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -240,7 +240,10 @@ func (ct *ConnTrack) connFor(pkt *PacketBuffer) (*conn, direction) {\nif err != nil {\nreturn nil, dirOriginal\n}\n+ return ct.connForTID(tid)\n+}\n+func (ct *ConnTrack) connForTID(tid tupleID) (*conn, direction) {\nbucket := ct.bucket(tid)\nnow := time.Now()\n@@ -604,3 +607,26 @@ func (ct *ConnTrack) reapTupleLocked(tuple *tuple, bucket int, now time.Time) bo\nreturn true\n}\n+\n+func (ct *ConnTrack) originalDst(epID TransportEndpointID) (tcpip.Address, uint16, *tcpip.Error) {\n+ // Lookup the connection. The reply's original destination\n+ // describes the original address.\n+ tid := tupleID{\n+ srcAddr: epID.LocalAddress,\n+ srcPort: epID.LocalPort,\n+ dstAddr: epID.RemoteAddress,\n+ dstPort: epID.RemotePort,\n+ transProto: header.TCPProtocolNumber,\n+ netProto: header.IPv4ProtocolNumber,\n+ }\n+ conn, _ := ct.connForTID(tid)\n+ if conn == nil {\n+ // Not a tracked connection.\n+ return \"\", 0, tcpip.ErrNotConnected\n+ } else if conn.manip == manipNone {\n+ // Unmanipulated connection.\n+ return \"\", 0, tcpip.ErrInvalidOptionValue\n+ }\n+\n+ return conn.original.dstAddr, conn.original.dstPort, nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -218,19 +218,16 @@ func (it *IPTables) Check(hook Hook, pkt *PacketBuffer, gso *GSO, r *Route, addr\n// Many users never configure iptables. Spare them the cost of rule\n// traversal if rules have never been set.\nit.mu.RLock()\n+ defer it.mu.RUnlock()\nif !it.modified {\n- it.mu.RUnlock()\nreturn true\n}\n- it.mu.RUnlock()\n// Packets are manipulated only if connection and matching\n// NAT rule exists.\nshouldTrack := it.connections.handlePacket(pkt, hook, gso, r)\n// Go through each table containing the hook.\n- it.mu.RLock()\n- defer it.mu.RUnlock()\npriorities := it.priorities[hook]\nfor _, tableID := range priorities {\n// If handlePacket already NATed the packet, we don't need to\n@@ -418,3 +415,9 @@ func (it *IPTables) checkRule(hook Hook, pkt *PacketBuffer, table Table, ruleIdx\n// All the matchers matched, so run the target.\nreturn rule.Target.Action(pkt, &it.connections, hook, gso, r, address)\n}\n+\n+// OriginalDst returns the original destination of redirected connections. It\n+// returns an error if the connection doesn't exist or isn't redirected.\n+func (it *IPTables) OriginalDst(epID TransportEndpointID) (tcpip.Address, uint16, *tcpip.Error) {\n+ return it.connections.originalDst(epID)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -954,6 +954,10 @@ type DefaultTTLOption uint8\n// classic BPF filter on a given endpoint.\ntype SocketDetachFilterOption int\n+// OriginalDestinationOption is used to get the original destination address\n+// and port of a redirected packet.\n+type OriginalDestinationOption FullAddress\n+\n// IPPacketInfo is the message structure for IP_PKTINFO.\n//\n// +stateify savable\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -2017,6 +2017,17 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\n*o = tcpip.TCPDeferAcceptOption(e.deferAccept)\ne.UnlockUser()\n+ case *tcpip.OriginalDestinationOption:\n+ ipt := e.stack.IPTables()\n+ addr, port, err := ipt.OriginalDst(e.ID)\n+ if err != nil {\n+ return err\n+ }\n+ *o = tcpip.OriginalDestinationOption{\n+ Addr: addr,\n+ Port: port,\n+ }\n+\ndefault:\nreturn tcpip.ErrUnknownProtocolOption\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/iptables/BUILD",
"new_path": "test/iptables/BUILD",
"diff": "@@ -9,6 +9,7 @@ go_library(\n\"filter_input.go\",\n\"filter_output.go\",\n\"iptables.go\",\n+ \"iptables_unsafe.go\",\n\"iptables_util.go\",\n\"nat.go\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "test/iptables/iptables_test.go",
"new_path": "test/iptables/iptables_test.go",
"diff": "@@ -371,3 +371,11 @@ func TestFilterAddrs(t *testing.T) {\n}\n}\n}\n+\n+func TestNATPreOriginalDst(t *testing.T) {\n+ singleTest(t, NATPreOriginalDst{})\n+}\n+\n+func TestNATOutOriginalDst(t *testing.T) {\n+ singleTest(t, NATOutOriginalDst{})\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/iptables/iptables_unsafe.go",
"diff": "+// Copyright 2020 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 iptables\n+\n+import (\n+ \"fmt\"\n+ \"syscall\"\n+ \"unsafe\"\n+)\n+\n+type originalDstError struct {\n+ errno syscall.Errno\n+}\n+\n+func (e originalDstError) Error() string {\n+ return fmt.Sprintf(\"errno (%d) when calling getsockopt(SO_ORIGINAL_DST): %v\", int(e.errno), e.errno.Error())\n+}\n+\n+// SO_ORIGINAL_DST gets the original destination of a redirected packet via\n+// getsockopt.\n+const SO_ORIGINAL_DST = 80\n+\n+func originalDestination4(connfd int) (syscall.RawSockaddrInet4, error) {\n+ var addr syscall.RawSockaddrInet4\n+ var addrLen uint32 = syscall.SizeofSockaddrInet4\n+ if errno := originalDestination(connfd, syscall.SOL_IP, unsafe.Pointer(&addr), &addrLen); errno != 0 {\n+ return syscall.RawSockaddrInet4{}, originalDstError{errno}\n+ }\n+ return addr, nil\n+}\n+\n+func originalDestination6(connfd int) (syscall.RawSockaddrInet6, error) {\n+ var addr syscall.RawSockaddrInet6\n+ var addrLen uint32 = syscall.SizeofSockaddrInet6\n+ if errno := originalDestination(connfd, syscall.SOL_IPV6, unsafe.Pointer(&addr), &addrLen); errno != 0 {\n+ return syscall.RawSockaddrInet6{}, originalDstError{errno}\n+ }\n+ return addr, nil\n+}\n+\n+func originalDestination(connfd int, level uintptr, optval unsafe.Pointer, optlen *uint32) syscall.Errno {\n+ _, _, errno := syscall.Syscall6(\n+ syscall.SYS_GETSOCKOPT,\n+ uintptr(connfd),\n+ level,\n+ SO_ORIGINAL_DST,\n+ uintptr(optval),\n+ uintptr(unsafe.Pointer(optlen)),\n+ 0)\n+ return errno\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/iptables/iptables_util.go",
"new_path": "test/iptables/iptables_util.go",
"diff": "package iptables\nimport (\n+ \"encoding/binary\"\n+ \"errors\"\n\"fmt\"\n\"net\"\n\"os/exec\"\n@@ -218,17 +220,58 @@ func filterAddrs(addrs []string, ipv6 bool) []string {\n// getInterfaceName returns the name of the interface other than loopback.\nfunc getInterfaceName() (string, bool) {\n- var ifname string\n+ iface, ok := getNonLoopbackInterface()\n+ if !ok {\n+ return \"\", false\n+ }\n+ return iface.Name, true\n+}\n+\n+func getInterfaceAddrs(ipv6 bool) ([]net.IP, error) {\n+ iface, ok := getNonLoopbackInterface()\n+ if !ok {\n+ return nil, errors.New(\"no non-loopback interface found\")\n+ }\n+ addrs, err := iface.Addrs()\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ // Get only IPv4 or IPv6 addresses.\n+ ips := make([]net.IP, 0, len(addrs))\n+ for _, addr := range addrs {\n+ parts := strings.Split(addr.String(), \"/\")\n+ var ip net.IP\n+ // To16() returns IPv4 addresses as IPv4-mapped IPv6 addresses.\n+ // So we check whether To4() returns nil to test whether the\n+ // address is v4 or v6.\n+ if v4 := net.ParseIP(parts[0]).To4(); ipv6 && v4 == nil {\n+ ip = net.ParseIP(parts[0]).To16()\n+ } else {\n+ ip = v4\n+ }\n+ if ip != nil {\n+ ips = append(ips, ip)\n+ }\n+ }\n+ return ips, nil\n+}\n+\n+func getNonLoopbackInterface() (net.Interface, bool) {\nif interfaces, err := net.Interfaces(); err == nil {\nfor _, intf := range interfaces {\nif intf.Name != \"lo\" {\n- ifname = intf.Name\n- break\n+ return intf, true\n+ }\n}\n}\n+ return net.Interface{}, false\n}\n- return ifname, ifname != \"\"\n+func htons(x uint16) uint16 {\n+ buf := make([]byte, 2)\n+ binary.BigEndian.PutUint16(buf, x)\n+ return binary.LittleEndian.Uint16(buf)\n}\nfunc localIP(ipv6 bool) string {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/iptables/nat.go",
"new_path": "test/iptables/nat.go",
"diff": "@@ -18,12 +18,11 @@ import (\n\"errors\"\n\"fmt\"\n\"net\"\n+ \"syscall\"\n\"time\"\n)\n-const (\n- redirectPort = 42\n-)\n+const redirectPort = 42\nfunc init() {\nRegisterTestCase(NATPreRedirectUDPPort{})\n@@ -42,6 +41,8 @@ func init() {\nRegisterTestCase(NATOutRedirectInvert{})\nRegisterTestCase(NATRedirectRequiresProtocol{})\nRegisterTestCase(NATLoopbackSkipsPrerouting{})\n+ RegisterTestCase(NATPreOriginalDst{})\n+ RegisterTestCase(NATOutOriginalDst{})\n}\n// NATPreRedirectUDPPort tests that packets are redirected to different port.\n@@ -471,6 +472,151 @@ func (NATLoopbackSkipsPrerouting) LocalAction(ip net.IP, ipv6 bool) error {\nreturn nil\n}\n+// NATPreOriginalDst tests that SO_ORIGINAL_DST returns the pre-NAT destination\n+// of PREROUTING NATted packets.\n+type NATPreOriginalDst struct{}\n+\n+// Name implements TestCase.Name.\n+func (NATPreOriginalDst) Name() string {\n+ return \"NATPreOriginalDst\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (NATPreOriginalDst) ContainerAction(ip net.IP, ipv6 bool) error {\n+ // Redirect incoming TCP connections to acceptPort.\n+ if err := natTable(ipv6, \"-A\", \"PREROUTING\",\n+ \"-p\", \"tcp\",\n+ \"--destination-port\", fmt.Sprintf(\"%d\", dropPort),\n+ \"-j\", \"REDIRECT\", \"--to-port\", fmt.Sprintf(\"%d\", acceptPort)); err != nil {\n+ return err\n+ }\n+\n+ addrs, err := getInterfaceAddrs(ipv6)\n+ if err != nil {\n+ return err\n+ }\n+ return listenForRedirectedConn(ipv6, addrs)\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (NATPreOriginalDst) LocalAction(ip net.IP, ipv6 bool) error {\n+ return connectTCP(ip, dropPort, sendloopDuration)\n+}\n+\n+// NATOutOriginalDst tests that SO_ORIGINAL_DST returns the pre-NAT destination\n+// of OUTBOUND NATted packets.\n+type NATOutOriginalDst struct{}\n+\n+// Name implements TestCase.Name.\n+func (NATOutOriginalDst) Name() string {\n+ return \"NATOutOriginalDst\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (NATOutOriginalDst) ContainerAction(ip net.IP, ipv6 bool) error {\n+ // Redirect incoming TCP connections to acceptPort.\n+ if err := natTable(ipv6, \"-A\", \"OUTPUT\", \"-p\", \"tcp\", \"-j\", \"REDIRECT\", \"--to-port\", fmt.Sprintf(\"%d\", acceptPort)); err != nil {\n+ return err\n+ }\n+\n+ connCh := make(chan error)\n+ go func() {\n+ connCh <- connectTCP(ip, dropPort, sendloopDuration)\n+ }()\n+\n+ if err := listenForRedirectedConn(ipv6, []net.IP{ip}); err != nil {\n+ return err\n+ }\n+ return <-connCh\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (NATOutOriginalDst) LocalAction(ip net.IP, ipv6 bool) error {\n+ // No-op.\n+ return nil\n+}\n+\n+func listenForRedirectedConn(ipv6 bool, originalDsts []net.IP) error {\n+ // The net package doesn't give guarantee access to the connection's\n+ // underlying FD, and thus we cannot call getsockopt. We have to use\n+ // traditional syscalls for SO_ORIGINAL_DST.\n+\n+ // Create the listening socket, bind, listen, and accept.\n+ family := syscall.AF_INET\n+ if ipv6 {\n+ family = syscall.AF_INET6\n+ }\n+ sockfd, err := syscall.Socket(family, syscall.SOCK_STREAM, 0)\n+ if err != nil {\n+ return err\n+ }\n+ defer syscall.Close(sockfd)\n+\n+ var bindAddr syscall.Sockaddr\n+ if ipv6 {\n+ bindAddr = &syscall.SockaddrInet6{\n+ Port: acceptPort,\n+ Addr: [16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // in6addr_any\n+ }\n+ } else {\n+ bindAddr = &syscall.SockaddrInet4{\n+ Port: acceptPort,\n+ Addr: [4]byte{0, 0, 0, 0}, // INADDR_ANY\n+ }\n+ }\n+ if err := syscall.Bind(sockfd, bindAddr); err != nil {\n+ return err\n+ }\n+\n+ if err := syscall.Listen(sockfd, 1); err != nil {\n+ return err\n+ }\n+\n+ connfd, _, err := syscall.Accept(sockfd)\n+ if err != nil {\n+ return err\n+ }\n+ defer syscall.Close(connfd)\n+\n+ // Verify that, despite listening on acceptPort, SO_ORIGINAL_DST\n+ // indicates the packet was sent to originalDst:dropPort.\n+ if ipv6 {\n+ got, err := originalDestination6(connfd)\n+ if err != nil {\n+ return err\n+ }\n+ // The original destination could be any of our IPs.\n+ for _, dst := range originalDsts {\n+ want := syscall.RawSockaddrInet6{\n+ Family: syscall.AF_INET6,\n+ Port: htons(dropPort),\n+ }\n+ copy(want.Addr[:], dst.To16())\n+ if got == want {\n+ return nil\n+ }\n+ }\n+ return fmt.Errorf(\"SO_ORIGINAL_DST returned %+v, but wanted one of %+v (note: port numbers are in network byte order)\", got, originalDsts)\n+ } else {\n+ got, err := originalDestination4(connfd)\n+ if err != nil {\n+ return err\n+ }\n+ // The original destination could be any of our IPs.\n+ for _, dst := range originalDsts {\n+ want := syscall.RawSockaddrInet4{\n+ Family: syscall.AF_INET,\n+ Port: htons(dropPort),\n+ }\n+ copy(want.Addr[:], dst.To4())\n+ if got == want {\n+ return nil\n+ }\n+ }\n+ return fmt.Errorf(\"SO_ORIGINAL_DST returned %+v, but wanted one of %+v (note: port numbers are in network byte order)\", got, originalDsts)\n+ }\n+}\n+\n// loopbackTests runs an iptables rule and ensures that packets sent to\n// dest:dropPort are received by localhost:acceptPort.\nfunc loopbackTest(ipv6 bool, dest net.IP, args ...string) error {\n"
}
] | Go | Apache License 2.0 | google/gvisor | iptables: support SO_ORIGINAL_DST
Envoy (#170) uses this to get the original destination of redirected
packets. |
259,858 | 31.07.2020 16:06:13 | 25,200 | a7d9aa6d5bfbed11c94578c6a2eb04ce75cbdbe5 | Use proper set-output syntax. | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/go.yml",
"new_path": ".github/workflows/go.yml",
"diff": "@@ -14,9 +14,9 @@ jobs:\n- id: setup\nrun: |\nif ! [[ -z \"${{ secrets.GO_TOKEN }}\" ]]; then\n- echo ::set-output has_token=true\n+ echo ::set-output name=has_token::true\nelse\n- echo ::set-output has_token=false\n+ echo ::set-output name=has_token::false\nfi\n- run: |\njq -nc '{\"state\": \"pending\", \"context\": \"go tests\"}' | \\\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use proper set-output syntax.
PiperOrigin-RevId: 324302828 |
259,853 | 31.07.2020 16:10:24 | 25,200 | fd5f4ffed1e425ec29d29477dc4e2a61420c1cf6 | test/socket_netlink_route: check that there is a route on local or main tables
A new network namespace has only the local route table. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_netlink_route.cc",
"new_path": "test/syscalls/linux/socket_netlink_route.cc",
"diff": "@@ -577,7 +577,10 @@ TEST(NetlinkRouteTest, GetRouteDump) {\nstd::cout << std::endl;\n- if (msg->rtm_table == RT_TABLE_MAIN) {\n+ // If the test is running in a new network namespace, it will have only\n+ // the local route table.\n+ if (msg->rtm_table == RT_TABLE_MAIN ||\n+ (!IsRunningOnGvisor() && msg->rtm_table == RT_TABLE_LOCAL)) {\nrouteFound = true;\ndstFound = rtDstFound && dstFound;\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | test/socket_netlink_route: check that there is a route on local or main tables
A new network namespace has only the local route table.
PiperOrigin-RevId: 324303629 |
259,983 | 31.07.2020 15:56:18 | 25,200 | e76c3c1064e2cb6ef79ea010705230a646369c49 | Fix MountFuseFilesystem tests failing
Before kernel version 4.16-rc6, fuse mount is protected by
capable(CAP_SYS_ADMIN). After this version, it uses
ns_capable(CAP_SYS_ADMIN) to protect. Before the 4.16 kernel,
it was not allowed to mount fuse file systems without the
global CAP_SYS_ADMIN.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/mount.cc",
"new_path": "test/syscalls/linux/mount.cc",
"diff": "@@ -326,6 +326,14 @@ TEST(MountTest, MountFuseFilesystemNoDevice) {\nSKIP_IF(IsRunningOnGvisor() && !IsFUSEEnabled());\nauto const dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+\n+ // Before kernel version 4.16-rc6, FUSE mount is protected by\n+ // capable(CAP_SYS_ADMIN). After this version, it uses\n+ // ns_capable(CAP_SYS_ADMIN) to protect. Before the 4.16 kernel, it was not\n+ // allowed to mount fuse file systems without the global CAP_SYS_ADMIN.\n+ int res = mount(\"\", dir.path().c_str(), \"fuse\", 0, \"\");\n+ SKIP_IF(!IsRunningOnGvisor() && res == -1 && errno == EPERM);\n+\nEXPECT_THAT(mount(\"\", dir.path().c_str(), \"fuse\", 0, \"\"),\nSyscallFailsWithErrno(EINVAL));\n}\n@@ -339,6 +347,12 @@ TEST(MountTest, MountFuseFilesystem) {\nstd::string mopts = \"fd=\" + std::to_string(fd.get());\nauto const dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+\n+ // See comments in MountFuseFilesystemNoDevice for the reason why we skip\n+ // EPERM when running on Linux.\n+ int res = mount(\"\", dir.path().c_str(), \"fuse\", 0, \"\");\n+ SKIP_IF(!IsRunningOnGvisor() && res == -1 && errno == EPERM);\n+\nauto const mount =\nASSERT_NO_ERRNO_AND_VALUE(Mount(\"\", dir.path(), \"fuse\", 0, mopts, 0));\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix MountFuseFilesystem tests failing
Before kernel version 4.16-rc6, fuse mount is protected by
capable(CAP_SYS_ADMIN). After this version, it uses
ns_capable(CAP_SYS_ADMIN) to protect. Before the 4.16 kernel,
it was not allowed to mount fuse file systems without the
global CAP_SYS_ADMIN.
Fixes #3360 |
259,891 | 31.07.2020 16:18:23 | 25,200 | fcc88a8b27ba1f7e572ebff00cf13460bdd4586b | Fix PHONY target typos | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -40,7 +40,7 @@ script:\n# On arm64, we need to create our own pipes for stderr and stdout,\n# otherwise we will not be able to open /dev/stderr. This is probably\n# due to AppArmor rules.\n- - bash -xeo pipefail -c 'uname -a && make smoke-test 2>&1 | cat'\n+ - bash -xeo pipefail -c 'uname -a && make smoke-tests 2>&1 | cat'\nbranches:\nexcept:\n# Skip copybara branches.\n"
},
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -117,7 +117,7 @@ debian: ## Builds the debian packages.\n@$(call submake,build OPTIONS=\"-c opt\" TARGETS=\"//runsc:runsc-debian\")\n.PHONY: debian\n-smoke-test: ## Runs a simple smoke test after build runsc.\n+smoke-tests: ## Runs a simple smoke test after build runsc.\n@$(call submake,run DOCKER_PRIVILEGED=\"\" ARGS=\"--alsologtostderr --network none --debug --TESTONLY-unsafe-nonroot=true --rootless do true\")\n.PHONY: smoke-tests\n@@ -218,7 +218,7 @@ packetimpact-tests: load-packetimpact\nroot-tests: load-basic-images\n@$(call submake,install-test-runtime)\n@$(call submake,sudo TARGETS=\"//test/root:root_test\" ARGS=\"-test.v\")\n-.PHONY: test-root\n+.PHONY: root-tests\n# Specific containerd version tests.\ncontainerd-test-%: load-basic_alpine load-basic_python load-basic_busybox load-basic_resolv load-basic_httpd install-test-runtime\n@@ -266,7 +266,7 @@ website-push: website-build ## Push a new image and update the service.\nwebsite-deploy: website-push ## Deploy a new version of the website.\n@gcloud run deploy $(WEBSITE_SERVICE) --platform=managed --region=$(WEBSITE_REGION) --project=$(WEBSITE_PROJECT) --image=$(WEBSITE_IMAGE)\n-.PHONY: website-push\n+.PHONY: website-deploy\n##\n## Repository builders.\n@@ -349,7 +349,7 @@ dev: ## Installs a set of local runtimes. Requires sudo.\nrefresh: ## Refreshes the runtime binary (for development only). Must have called 'dev' or 'install-test-runtime' first.\n@mkdir -p \"$(RUNTIME_DIR)\"\n@$(call submake,copy TARGETS=runsc DESTINATION=\"$(RUNTIME_BIN)\")\n-.PHONY: install\n+.PHONY: refresh\ninstall-test-runtime: ## Installs the runtime for testing. Requires sudo.\n@$(call submake,refresh ARGS=\"--net-raw --TESTONLY-test-name-env=RUNSC_TEST_NAME --debug --strace --log-packets $(ARGS)\")\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix PHONY target typos
PiperOrigin-RevId: 324305107 |
259,858 | 03.08.2020 09:07:43 | 25,200 | 10f6c41bbd5dbc84c57aedb4cb86e7dfd59a8114 | Include shim binaries in the Go branch. | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/go.yml",
"new_path": ".github/workflows/go.yml",
"diff": "@@ -49,7 +49,9 @@ jobs:\nkey: ${{ runner.os }}-bazel-${{ hashFiles('WORKSPACE') }}\nrestore-keys: |\n${{ runner.os }}-bazel-\n- - run: make build TARGETS=\"//:gopath\"\n+ - run: |\n+ rm -rf bazel-bin/gopath\n+ make build TARGETS=\"//:gopath\"\n- run: tools/go_branch.sh\n- run: git checkout go && git clean -f\n- run: go build ./...\n"
},
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -58,7 +58,7 @@ Make sure the following dependencies are installed:\nBuild and install the `runsc` binary:\n-```\n+```sh\nmake runsc\nsudo cp ./bazel-bin/runsc/linux_amd64_pure_stripped/runsc /usr/local/bin\n```\n@@ -67,14 +67,14 @@ sudo cp ./bazel-bin/runsc/linux_amd64_pure_stripped/runsc /usr/local/bin\nTo run standard test suites, you can use:\n-```\n+```sh\nmake unit-tests\nmake tests\n```\nTo run specific tests, you can specify the target:\n-```\n+```sh\nmake test TARGETS=\"//runsc:version_test\"\n```\n@@ -84,12 +84,19 @@ This project uses [bazel][bazel] to build and manage dependencies. A synthetic\n`go` branch is maintained that is compatible with standard `go` tooling for\nconvenience.\n-For example, to build `runsc` directly from this branch:\n+For example, to build and install `runsc` directly from this branch:\n-```\n+```sh\necho \"module runsc\" > go.mod\nGO111MODULE=on go get gvisor.dev/gvisor/runsc@go\n-CGO_ENABLED=0 GO111MODULE=on go install gvisor.dev/gvisor/runsc\n+CGO_ENABLED=0 GO111MODULE=on sudo -E go build -o /usr/local/bin/runsc gvisor.dev/gvisor/runsc\n+```\n+\n+Subsequently, you can build and install the shim binaries for `containerd`:\n+\n+```sh\n+GO111MODULE=on sudo -E go build -o /usr/local/bin/gvisor-containerd-shim gvisor.dev/gvisor/shim/v1\n+GO111MODULE=on sudo -E go build -o /usr/local/bin/containerd-shim-runsc-v1 gvisor.dev/gvisor/shim/v2\n```\nNote that this branch is supported in a best effort capacity, and direct\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/go_branch.sh",
"new_path": "tools/go_branch.sh",
"diff": "@@ -40,10 +40,15 @@ trap finish EXIT\n# Record the current working commit.\ndeclare -r head=$(git describe --always)\n-# We expect to have an existing go branch that we will use as the basis for\n-# this commit. That branch may be empty, but it must exist.\n+# We expect to have an existing go branch that we will use as the basis for this\n+# commit. That branch may be empty, but it must exist. We search for this branch\n+# using the local branch, the \"origin\" branch, and other remotes, in order.\ngit fetch --all\n-declare -r go_branch=$(git show-ref --hash go)\n+declare -r go_branch=$( \\\n+ git show-ref --hash refs/heads/go || \\\n+ git show-ref --hash refs/remotes/origin/go || \\\n+ git show-ref --hash go | head -n 1 \\\n+)\n# Clone the current repository to the temporary directory, and check out the\n# current go_branch directory. We move to the new repository for convenience.\n@@ -66,6 +71,11 @@ git checkout -b go \"${go_branch}\"\ngit merge --no-commit --strategy ours ${head} || \\\ngit merge --allow-unrelated-histories --no-commit --strategy ours ${head}\n+# Normalize the permissions on the old branch. Note that they should be\n+# normalized if constructed by this tool, but we do so before the rsync.\n+find . -type f -exec chmod 0644 {} \\;\n+find . -type d -exec chmod 0755 {} \\;\n+\n# Sync the entire gopath_dir.\nrsync --recursive --verbose --delete --exclude .git -L \"${gopath_dir}/\" .\n@@ -86,7 +96,11 @@ EOF\n# There are a few solitary files that can get left behind due to the way bazel\n# constructs the gopath target. Note that we don't find all Go files here\n# because they may correspond to unused templates, etc.\n-cp \"${repo_orig}\"/runsc/*.go runsc/\n+declare -ar binaries=( \"runsc\" \"shim/v1\" \"shim/v2\" )\n+for target in \"${binaries[@]}\"; do\n+ mkdir -p \"${target}\"\n+ cp \"${repo_orig}/${target}\"/*.go \"${target}/\"\n+done\n# Normalize all permissions. The way bazel constructs the :gopath tree may leave\n# some strange permissions on files. We don't have anything in this tree that\n"
}
] | Go | Apache License 2.0 | google/gvisor | Include shim binaries in the Go branch.
PiperOrigin-RevId: 324615016 |
259,858 | 03.08.2020 11:20:31 | 25,200 | e3c349d21957edbc124647e122f5d07e2e853690 | Fix syntax error in issue_reviver. | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/issue_reviver.yml",
"new_path": ".github/workflows/issue_reviver.yml",
"diff": "@@ -8,9 +8,9 @@ jobs:\nruns-on: ubuntu-latest\nsteps:\n- uses: actions/checkout@v2\n- if: github.repository == \"google/gvisor\"\n+ if: github.repository == 'google/gvisor'\n- run: make run TARGETS=\"//tools/issue_reviver\"\n- if: github.repository == \"google/gvisor\"\n+ if: github.repository == 'google/gvisor'\nenv:\nGITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\nGITHUB_REPOSITORY: ${{ github.repository }}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix syntax error in issue_reviver.
PiperOrigin-RevId: 324642975 |
259,860 | 03.08.2020 12:30:23 | 25,200 | 1fbbc795ef8918006214032d96fa88b8a21e5e0a | Add inotify events for fallocate and tests for fallocate/sendfile.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/setstat.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/setstat.go",
"diff": "@@ -254,11 +254,12 @@ func Fallocate(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sys\nreturn 0, nil, syserror.EFBIG\n}\n- return 0, nil, file.Allocate(t, mode, uint64(offset), uint64(length))\n+ if err := file.Allocate(t, mode, uint64(offset), uint64(length)); err != nil {\n+ return 0, nil, err\n+ }\n- // File length modified, generate notification.\n- // TODO(gvisor.dev/issue/1479): Reenable when Inotify is ported.\n- // file.Dirent.InotifyEvent(linux.IN_MODIFY, 0)\n+ file.Dentry().InotifyWithParent(linux.IN_MODIFY, 0, vfs.PathEvent)\n+ return 0, nil, nil\n}\n// Utime implements Linux syscall utime(2).\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/inotify.cc",
"new_path": "test/syscalls/linux/inotify.cc",
"diff": "#include <sys/epoll.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n+#include <sys/sendfile.h>\n#include <sys/time.h>\n#include <sys/xattr.h>\n@@ -1681,6 +1682,60 @@ TEST(Inotify, EpollNoDeadlock) {\n}\n}\n+TEST(Inotify, Fallocate) {\n+ const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR));\n+\n+ const FileDescriptor inotify_fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));\n+ const int wd = ASSERT_NO_ERRNO_AND_VALUE(\n+ InotifyAddWatch(inotify_fd.get(), file.path(), IN_ALL_EVENTS));\n+\n+ // Do an arbitrary modification with fallocate.\n+ ASSERT_THAT(fallocate(fd.get(), 0, 0, 123), SyscallSucceeds());\n+ std::vector<Event> events =\n+ ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));\n+ EXPECT_THAT(events, Are({Event(IN_MODIFY, wd)}));\n+}\n+\n+TEST(Inotify, Sendfile) {\n+ SKIP_IF(IsRunningWithVFS1());\n+\n+ const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(\n+ TempPath::CreateFileWith(root.path(), \"x\", 0644));\n+ const TempPath out_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ const FileDescriptor in =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDONLY));\n+ const FileDescriptor out =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(out_file.path(), O_WRONLY));\n+\n+ // Create separate inotify instances for the in and out fds. If both watches\n+ // were on the same instance, we would have discrepancies between Linux and\n+ // gVisor (order of events, duplicate events), which is not that important\n+ // since inotify is asynchronous anyway.\n+ const FileDescriptor in_inotify =\n+ ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));\n+ const FileDescriptor out_inotify =\n+ ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));\n+ const int in_wd = ASSERT_NO_ERRNO_AND_VALUE(\n+ InotifyAddWatch(in_inotify.get(), in_file.path(), IN_ALL_EVENTS));\n+ const int out_wd = ASSERT_NO_ERRNO_AND_VALUE(\n+ InotifyAddWatch(out_inotify.get(), out_file.path(), IN_ALL_EVENTS));\n+\n+ ASSERT_THAT(sendfile(out.get(), in.get(), /*offset=*/nullptr, 1),\n+ SyscallSucceeds());\n+\n+ // Expect a single access event and a single modify event.\n+ std::vector<Event> in_events =\n+ ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(in_inotify.get()));\n+ std::vector<Event> out_events =\n+ ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(out_inotify.get()));\n+ EXPECT_THAT(in_events, Are({Event(IN_ACCESS, in_wd)}));\n+ EXPECT_THAT(out_events, Are({Event(IN_MODIFY, out_wd)}));\n+}\n+\n// On Linux, inotify behavior is not very consistent with splice(2). We try our\n// best to emulate Linux for very basic calls to splice.\nTEST(Inotify, SpliceOnWatchTarget) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add inotify events for fallocate and tests for fallocate/sendfile.
Updates #1479, #2923.
PiperOrigin-RevId: 324658826 |
259,860 | 03.08.2020 15:23:05 | 25,200 | 5626ccf61f718d80d46049e11d040a3a8fc72fb9 | Remove old TODO.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/fd.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/fd.go",
"diff": "@@ -208,7 +208,7 @@ func Fcntl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\ncase linux.F_SETLK, linux.F_SETLKW:\nreturn 0, nil, posixLock(t, args, file, cmd)\ndefault:\n- // TODO(gvisor.dev/issue/2920): Everything else is not yet supported.\n+ // Everything else is not yet supported.\nreturn 0, nil, syserror.EINVAL\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove old TODO.
Fixes #2920.
PiperOrigin-RevId: 324695118 |
259,907 | 03.08.2020 18:15:11 | 25,200 | ad7c9fc4c3c027ea7ed211a6bdb35c38156280e6 | [vfs2] Implement /sys/devices/system/cpu/cpuX.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/sys/sys.go",
"new_path": "pkg/sentry/fsimpl/sys/sys.go",
"diff": "@@ -30,6 +30,7 @@ import (\n// Name is the default filesystem name.\nconst Name = \"sysfs\"\n+const defaultSysDirMode = linux.FileMode(0755)\n// FilesystemType implements vfs.FilesystemType.\ntype FilesystemType struct{}\n@@ -57,9 +58,6 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\ndevMinor: devMinor,\n}\nfs.VFSFilesystem().Init(vfsObj, &fsType, fs)\n- k := kernel.KernelFromContext(ctx)\n- maxCPUCores := k.ApplicationCores()\n- defaultSysDirMode := linux.FileMode(0755)\nroot := fs.newDir(creds, defaultSysDirMode, map[string]*kernfs.Dentry{\n\"block\": fs.newDir(creds, defaultSysDirMode, nil),\n@@ -70,11 +68,7 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n\"dev\": fs.newDir(creds, defaultSysDirMode, nil),\n\"devices\": fs.newDir(creds, defaultSysDirMode, map[string]*kernfs.Dentry{\n\"system\": fs.newDir(creds, defaultSysDirMode, map[string]*kernfs.Dentry{\n- \"cpu\": fs.newDir(creds, defaultSysDirMode, map[string]*kernfs.Dentry{\n- \"online\": fs.newCPUFile(creds, maxCPUCores, linux.FileMode(0444)),\n- \"possible\": fs.newCPUFile(creds, maxCPUCores, linux.FileMode(0444)),\n- \"present\": fs.newCPUFile(creds, maxCPUCores, linux.FileMode(0444)),\n- }),\n+ \"cpu\": cpuDir(ctx, fs, creds),\n}),\n}),\n\"firmware\": fs.newDir(creds, defaultSysDirMode, nil),\n@@ -86,6 +80,20 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nreturn fs.VFSFilesystem(), root.VFSDentry(), nil\n}\n+func cpuDir(ctx context.Context, fs *filesystem, creds *auth.Credentials) *kernfs.Dentry {\n+ k := kernel.KernelFromContext(ctx)\n+ maxCPUCores := k.ApplicationCores()\n+ children := map[string]*kernfs.Dentry{\n+ \"online\": fs.newCPUFile(creds, maxCPUCores, linux.FileMode(0444)),\n+ \"possible\": fs.newCPUFile(creds, maxCPUCores, linux.FileMode(0444)),\n+ \"present\": fs.newCPUFile(creds, maxCPUCores, linux.FileMode(0444)),\n+ }\n+ for i := uint(0); i < maxCPUCores; i++ {\n+ children[fmt.Sprintf(\"cpu%d\", i)] = fs.newDir(creds, linux.FileMode(0555), nil)\n+ }\n+ return fs.newDir(creds, defaultSysDirMode, children)\n+}\n+\n// Release implements vfs.FilesystemImpl.Release.\nfunc (fs *filesystem) Release(ctx context.Context) {\nfs.Filesystem.VFSFilesystem().VirtualFilesystem().PutAnonBlockDevMinor(fs.devMinor)\n"
}
] | Go | Apache License 2.0 | google/gvisor | [vfs2] Implement /sys/devices/system/cpu/cpuX.
Fixes #3364
PiperOrigin-RevId: 324724614 |
259,884 | 04.08.2020 01:05:42 | 25,200 | a02b7534f21d4f963ace890e80d7bf17e0d5d10f | Fix grouping and ordering of website menus
Groups subcategories and sorts their pages by weight properly. Subcategories
are sorted by name. Pages within subcategories are sorted by weight. | [
{
"change_type": "MODIFY",
"old_path": "BUILD",
"new_path": "BUILD",
"diff": "@@ -30,7 +30,7 @@ doc(\npermalink = \"/community/governance/\",\nsubcategory = \"Community\",\nvisibility = [\"//website:__pkg__\"],\n- weight = \"91\",\n+ weight = \"20\",\n)\ndoc(\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/BUILD",
"new_path": "g3doc/BUILD",
"diff": "@@ -31,7 +31,7 @@ doc(\ncategory = \"Project\",\npermalink = \"/community/\",\nsubcategory = \"Community\",\n- weight = \"95\",\n+ weight = \"10\",\n)\ndoc(\n@@ -40,5 +40,5 @@ doc(\ncategory = \"Project\",\npermalink = \"/community/style_guide/\",\nsubcategory = \"Community\",\n- weight = \"10\",\n+ weight = \"99\",\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/tutorials/BUILD",
"new_path": "g3doc/user_guide/tutorials/BUILD",
"diff": "@@ -11,16 +11,7 @@ doc(\ncategory = \"User Guide\",\npermalink = \"/docs/tutorials/docker/\",\nsubcategory = \"Tutorials\",\n- weight = \"21\",\n-)\n-\n-doc(\n- name = \"cni\",\n- src = \"cni.md\",\n- category = \"User Guide\",\n- permalink = \"/docs/tutorials/cni/\",\n- subcategory = \"Tutorials\",\n- weight = \"22\",\n+ weight = \"10\",\n)\ndoc(\n@@ -33,5 +24,14 @@ doc(\n],\npermalink = \"/docs/tutorials/kubernetes/\",\nsubcategory = \"Tutorials\",\n- weight = \"33\",\n+ weight = \"20\",\n+)\n+\n+doc(\n+ name = \"cni\",\n+ src = \"cni.md\",\n+ category = \"User Guide\",\n+ permalink = \"/docs/tutorials/cni/\",\n+ subcategory = \"Tutorials\",\n+ weight = \"30\",\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "website/_layouts/docs.html",
"new_path": "website/_layouts/docs.html",
"diff": "@@ -14,30 +14,25 @@ categories:\n{% for category in layout.categories %}\n<h3>{{ category }}</h3>\n<ul class=\"sidebar-nav\">\n- {% assign sorted_pages = site.pages | where: 'layout', 'docs' | where: 'category', category | sort: 'weight' | sort: 'subcategory' %}\n- {% assign subcategory = nil %}\n- {% for p in sorted_pages %}\n- {% if p.subcategory != subcategory %}\n- {% if subcategory != nil %}\n- </ul>\n- </li>\n- {% endif %}\n- {% assign subcategory = p.subcategory %}\n- {% if subcategory != nil %}\n+ {% assign subcats = site.pages | where: 'layout', 'docs' | where: 'category', category | group_by: 'subcategory' | sort: 'name', 'first' %}\n+ {% for subcategory in subcats %}\n+ {% assign sorted_pages = subcategory.items | sort: 'weight', 'last' %}\n+ {% if subcategory.name != \"\" %}\n{% assign ac = \"aria-controls\" %}\n- {% assign cid = p.category | remove: \" \" | downcase %}\n- {% assign sid = p.subcategory | remove: \" \" | downcase %}\n+ {% assign cid = category | remove: \" \" | downcase %}\n+ {% assign sid = subcategory.name | remove: \" \" | downcase %}\n<li>\n- <a class=\"sidebar-nav-heading\" data-toggle=\"collapse\" href=\"#{{ cid }}-{{ sid }}\" aria-expanded=\"false\" {{ ac }}=\"{{ cid }}-{{ sid }}\">{{ subcategory }}<span class=\"caret\"></span></a>\n+ <a class=\"sidebar-nav-heading\" data-toggle=\"collapse\" href=\"#{{ cid }}-{{ sid }}\" aria-expanded=\"false\" {{ ac }}=\"{{ cid }}-{{ sid }}\">{{ subcategory.name }}<span class=\"caret\"></span></a>\n<ul class=\"collapse sidebar-nav sidebar-submenu\" id=\"{{ cid }}-{{ sid }}\">\n{% endif %}\n- {% endif %}\n+ {% for p in sorted_pages %}\n<li><a href=\"{{ p.url }}\">{{ p.title }}</a></li>\n{% endfor %}\n- {% if subcategory != nil %}\n- </ul>\n+ {% if subcategory.name != \"\" %}\n</li>\n+ </ul>\n{% endif %}\n+ {% endfor %}\n</ul>\n{% endfor %}\n</nav>\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix grouping and ordering of website menus
Groups subcategories and sorts their pages by weight properly. Subcategories
are sorted by name. Pages within subcategories are sorted by weight.
PiperOrigin-RevId: 324766128 |
259,962 | 04.08.2020 09:04:53 | 25,200 | 1bdadbc4f84bf5aacd63d1f486d4c4610dea4110 | Fix broken httpd_test. | [
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/network/httpd_test.go",
"new_path": "test/benchmarks/network/httpd_test.go",
"diff": "@@ -68,13 +68,13 @@ func BenchmarkHttpdConcurrency(b *testing.B) {\n// BenchmarkHttpdDocSize iterates over different sized payloads, testing how\n// well the runtime handles sending different payload sizes.\nfunc BenchmarkHttpdDocSize(b *testing.B) {\n- benchmarkHttpDocSize(b, false /* reverse */)\n+ benchmarkHttpdDocSize(b, false /* reverse */)\n}\n// BenchmarkReverseHttpdDocSize iterates over different sized payloads, testing\n// how well the runtime handles receiving different payload sizes.\nfunc BenchmarkReverseHttpdDocSize(b *testing.B) {\n- benchmarkHttpDocSize(b, true /* reverse */)\n+ benchmarkHttpdDocSize(b, true /* reverse */)\n}\nfunc benchmarkHttpdDocSize(b *testing.B, reverse bool) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix broken httpd_test.
PiperOrigin-RevId: 324822613 |
259,907 | 04.08.2020 09:49:33 | 25,200 | 7dfcf727a5730b15020f136282a1ede15144a268 | [runtime tests] Fix nodejs runtime tests.
Exclude flaky tests.
Bump timeout.
Un-exclude passing tests to increase testing surface.
Create/Update bugs for tests that pass on runc but fail on runsc. | [
{
"change_type": "MODIFY",
"old_path": "test/runtimes/exclude_nodejs12.4.0.csv",
"new_path": "test/runtimes/exclude_nodejs12.4.0.csv",
"diff": "test name,bug id,comment\nbenchmark/test-benchmark-fs.js,,\n-benchmark/test-benchmark-module.js,,\nbenchmark/test-benchmark-napi.js,,\ndoctool/test-make-doc.js,b/68848110,Expected to fail.\n-fixtures/test-error-first-line-offset.js,,\n-fixtures/test-fs-readfile-error.js,,\n-fixtures/test-fs-stat-sync-overflow.js,,\n-internet/test-dgram-broadcast-multi-process.js,,\n-internet/test-dgram-multicast-multi-process.js,,\n-internet/test-dgram-multicast-set-interface-lo.js,,\n+internet/test-dgram-multicast-set-interface-lo.js,b/162798882,\ninternet/test-doctool-versions.js,,\ninternet/test-uv-threadpool-schedule.js,,\nparallel/test-cluster-dgram-reuse.js,b/64024294,\nparallel/test-dgram-bind-fd.js,b/132447356,\n-parallel/test-dgram-create-socket-handle-fd.js,b/132447238,\n-parallel/test-dgram-createSocket-type.js,b/68847739,\nparallel/test-dgram-socket-buffer-size.js,b/68847921,\nparallel/test-dns-channel-timeout.js,b/161893056,\nparallel/test-fs-access.js,,\n-parallel/test-fs-write-stream-double-close.js,,\n+parallel/test-fs-watchfile.js,,Flaky - File already exists error\nparallel/test-fs-write-stream-throw-type-error.js,b/110226209,\n-parallel/test-fs-write-stream.js,,\n-parallel/test-http2-respond-file-error-pipe-offset.js,,\n-parallel/test-os.js,,\n+parallel/test-http-writable-true-after-close.js,,Flaky - Mismatched <anonymous> function calls. Expected exactly 1 actual 2\n+parallel/test-os.js,b/63997097,\nparallel/test-process-uid-gid.js,,\n-pseudo-tty/test-assert-colors.js,,\n-pseudo-tty/test-assert-no-color.js,,\n-pseudo-tty/test-assert-position-indicator.js,,\n-pseudo-tty/test-async-wrap-getasyncid-tty.js,,\n-pseudo-tty/test-fatal-error.js,,\n-pseudo-tty/test-handle-wrap-isrefed-tty.js,,\n-pseudo-tty/test-readable-tty-keepalive.js,,\n-pseudo-tty/test-set-raw-mode-reset-process-exit.js,,\n-pseudo-tty/test-set-raw-mode-reset-signal.js,,\n-pseudo-tty/test-set-raw-mode-reset.js,,\n-pseudo-tty/test-stderr-stdout-handle-sigwinch.js,,\n-pseudo-tty/test-stdout-read.js,,\n-pseudo-tty/test-tty-color-support.js,,\n-pseudo-tty/test-tty-isatty.js,,\n-pseudo-tty/test-tty-stdin-call-end.js,,\n-pseudo-tty/test-tty-stdin-end.js,,\n-pseudo-tty/test-stdin-write.js,,\n-pseudo-tty/test-tty-stdout-end.js,,\n-pseudo-tty/test-tty-stdout-resize.js,,\n-pseudo-tty/test-tty-stream-constructors.js,,\n-pseudo-tty/test-tty-window-size.js,,\n-pseudo-tty/test-tty-wrap.js,,\n+parallel/test-tls-cli-min-version-1.0.js,,Flaky - EADDRINUSE\n+parallel/test-tls-cli-min-version-1.3.js,,Flaky - EADDRINUSE\n+parallel/test-tls-cli-max-version-1.2,,Flaky - EADDRINUSE\n+parallel/test-tls-min-max-version.js,,Flaky - EADDRINUSE\n+pseudo-tty/test-assert-colors.js,b/162801321,\n+pseudo-tty/test-assert-no-color.js,b/162801321,\n+pseudo-tty/test-assert-position-indicator.js,b/162801321,\n+pseudo-tty/test-async-wrap-getasyncid-tty.js,b/162801321,\n+pseudo-tty/test-fatal-error.js,b/162801321,\n+pseudo-tty/test-handle-wrap-isrefed-tty.js,b/162801321,\n+pseudo-tty/test-readable-tty-keepalive.js,b/162801321,\n+pseudo-tty/test-set-raw-mode-reset-process-exit.js,b/162801321,\n+pseudo-tty/test-set-raw-mode-reset-signal.js,b/162801321,\n+pseudo-tty/test-set-raw-mode-reset.js,b/162801321,\n+pseudo-tty/test-stderr-stdout-handle-sigwinch.js,b/162801321,\n+pseudo-tty/test-stdout-read.js,b/162801321,\n+pseudo-tty/test-tty-color-support.js,b/162801321,\n+pseudo-tty/test-tty-isatty.js,b/162801321,\n+pseudo-tty/test-tty-stdin-call-end.js,b/162801321,\n+pseudo-tty/test-tty-stdin-end.js,b/162801321,\n+pseudo-tty/test-stdin-write.js,b/162801321,\n+pseudo-tty/test-tty-stdout-end.js,b/162801321,\n+pseudo-tty/test-tty-stdout-resize.js,b/162801321,\n+pseudo-tty/test-tty-stream-constructors.js,b/162801321,\n+pseudo-tty/test-tty-window-size.js,b/162801321,\n+pseudo-tty/test-tty-wrap.js,b/162801321,\npummel/test-net-pingpong.js,,\n-pummel/test-vm-memleak.js,,\n+pummel/test-vm-memleak.js,b/162799436,\n+sequential/test-child-process-pass-fd.js,b/63926391,Flaky\n+sequential/test-https-connect-localport.js,,Flaky - EADDRINUSE\nsequential/test-net-bytes-per-incoming-chunk-overhead.js,,flaky - timeout\ntick-processor/test-tick-processor-builtin.js,,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runtimes/proctor/nodejs.go",
"new_path": "test/runtimes/proctor/nodejs.go",
"diff": "@@ -41,6 +41,6 @@ func (nodejsRunner) ListTests() ([]string, error) {\n// TestCmds implements TestRunner.TestCmds.\nfunc (nodejsRunner) TestCmds(tests []string) []*exec.Cmd {\n- args := append([]string{filepath.Join(\"tools\", \"test.py\")}, tests...)\n+ args := append([]string{filepath.Join(\"tools\", \"test.py\"), \"--timeout=180\"}, tests...)\nreturn []*exec.Cmd{exec.Command(\"/usr/bin/python\", args...)}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | [runtime tests] Fix nodejs runtime tests.
- Exclude flaky tests.
- Bump timeout.
- Un-exclude passing tests to increase testing surface.
- Create/Update bugs for tests that pass on runc but fail on runsc.
PiperOrigin-RevId: 324830840 |
259,891 | 04.08.2020 10:01:05 | 25,200 | 12c2c6ae303c97be5ad8e62b67ca265e2c4e0ba6 | docs: tools/images.mk does not exist. | [
{
"change_type": "MODIFY",
"old_path": "images/README.md",
"new_path": "images/README.md",
"diff": "@@ -7,7 +7,7 @@ Note that all these images must be pushed to the testing project hosted on\ncontinuous integration. This will speed up loading as images will not need to be\nbuilt from scratch for each test run.\n-Image tooling is accessible via `make`, specifically via `tools/images.mk`.\n+Image tooling is accessible via `make`, specifically via `images/Makefile`.\n## Why make?\n"
}
] | Go | Apache License 2.0 | google/gvisor | docs: tools/images.mk does not exist.
PiperOrigin-RevId: 324833018 |
259,983 | 04.08.2020 12:27:55 | 25,200 | 21d0334e7f4a98ec49e7f46cacf2d51258eaec33 | Add FUSE integration test
This commit adds an integration test framework for FUSE support. Please
refer to the test example and test/fuse/README.md for further details.
Fixes | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/fuse_tests.sh",
"diff": "+#!/bin/bash\n+\n+# Copyright 2020 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+source $(dirname $0)/common.sh\n+\n+# Run all vfs2_fuse system call tests.\n+test --test_tag_filters=fuse //test/fuse/...\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/fuse/BUILD",
"diff": "+package(licenses = [\"notice\"])\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/fuse/README.md",
"diff": "+# gVisor FUSE Test Suite\n+\n+This is an integration test suite for fuse(4) filesystem. It runs under both\n+gVisor and Linux, and ensures compatibility between the two. This test suite is\n+based on system calls test.\n+\n+This document describes the framework of fuse integration test and the\n+guidelines that should be followed when adding new fuse tests.\n+\n+## Integration Test Framework\n+\n+Please refer to the figure below. `>` is entering the function, `<` is leaving\n+the function, and `=` indicates sequentially entering and leaving.\n+\n+```\n+ | Client (Test Main Process) | Server (FUSE Daemon)\n+ | |\n+ | >TEST_F() |\n+ | >SetUp() |\n+ | =MountFuse() |\n+ | >SetUpFuseServer() |\n+ | [create communication pipes] |\n+ | =fork() | =fork()\n+ | >WaitCompleted() |\n+ | [wait for MarkDone()] |\n+ | | =ConsumeFuseInit()\n+ | | =MarkDone()\n+ | <WaitCompleted() |\n+ | <SetUpFuseServer() |\n+ | <SetUp() |\n+ | >SetExpected() |\n+ | [construct expected reaction] |\n+ | | >FuseLoop()\n+ | | >ReceiveExpected()\n+ | | [wait data from pipe]\n+ | [write data to pipe] |\n+ | [wait for MarkDone()] |\n+ | | [save data to memory]\n+ | | =MarkDone()\n+ | <SetExpected() |\n+ | | <ReceiveExpected()\n+ | | >read()\n+ | | [wait for fs operation]\n+ | >[Do fs operation] |\n+ | [wait for fs response] |\n+ | | <read()\n+ | | =CompareRequest()\n+ | | =write() [write fs response]\n+ | <[Do fs operation] |\n+ | =[Test fs operation result] |\n+ | =[wait for MarkDone()] |\n+ | | =MarkDone()\n+ | >TearDown() |\n+ | =UnmountFuse() |\n+ | <TearDown() |\n+ | <TEST_F() |\n+```\n+\n+## Running the tests\n+\n+Based on syscall tests, fuse tests can run in different environments. To enable\n+fuse testing environment, the test targets should be appended with `_fuse`.\n+\n+For example, to run fuse test in `stat_test.cc`:\n+\n+```bash\n+$ bazel test //test/fuse:stat_test_runsc_ptrace_vfs2_fuse\n+```\n+\n+Test all targets tagged with fuse:\n+\n+```bash\n+$ bazel test --test_tag_filters=fuse //test/fuse/...\n+```\n+\n+## Writing a new FUSE test\n+\n+1. Add test targets in `BUILD` and `linux/BUILD`.\n+2. Inherit your test from `FuseTest` base class. It allows you to:\n+ - Run a fake FUSE server in background during each test setup.\n+ - Create pipes for communication and provide utility functions.\n+ - Stop FUSE server after test completes.\n+3. Customize your comparison function for request assessment in FUSE server.\n+4. Add the mapping of the size of structs if you are working on new FUSE opcode.\n+ - Please update `FuseTest::GetPayloadSize()` for each new FUSE opcode.\n+5. Build the expected request-response pair of your FUSE operation.\n+6. Call `SetExpected()` function to inject the expected reaction.\n+7. Check the response and/or errors.\n+8. Finally call `WaitCompleted()` to ensure the FUSE server acts correctly.\n+\n+A few customized matchers used in syscalls test are encouraged to test the\n+outcome of filesystem operations. Such as:\n+\n+```cc\n+SyscallSucceeds()\n+SyscallSucceedsWithValue(...)\n+SyscallFails()\n+SyscallFailsWithErrno(...)\n+```\n+\n+Please refer to [test/syscalls/README.md](../syscalls/README.md) for further\n+details.\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/fuse/linux/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"cc_library\", \"gtest\")\n+\n+package(\n+ default_visibility = [\"//:sandbox\"],\n+ licenses = [\"notice\"],\n+)\n+\n+cc_library(\n+ name = \"fuse_base\",\n+ testonly = 1,\n+ srcs = [\n+ \"fuse_base.h\",\n+ \"fuse_base.cc\",\n+ ],\n+ deps = [\n+ gtest,\n+ \"//test/util:posix_error\",\n+ \"//test/util:test_util\",\n+ \"@com_google_absl//absl/strings:str_format\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/fuse/linux/fuse_base.cc",
"diff": "+// Copyright 2020 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 \"fuse_base.h\"\n+\n+#include <fcntl.h>\n+#include <linux/fuse.h>\n+#include <stdio.h>\n+#include <string.h>\n+#include <sys/mount.h>\n+#include <sys/stat.h>\n+#include <sys/uio.h>\n+#include <unistd.h>\n+\n+#include <iostream>\n+\n+#include \"absl/strings/str_format.h\"\n+#include \"gmock/gmock.h\"\n+#include \"gtest/gtest.h\"\n+#include \"test/util/posix_error.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+void FuseTest::SetUp() {\n+ MountFuse();\n+ SetUpFuseServer();\n+}\n+\n+void FuseTest::TearDown() { UnmountFuse(); }\n+\n+// Since CompareRequest is running in background thread, gTest assertions and\n+// expectations won't directly reflect the test result. However, the FUSE\n+// background server still connects to the same standard I/O as testing main\n+// thread. So EXPECT_XX can still be used to show different results. To\n+// ensure failed testing result is observable, return false and the result\n+// will be sent to test main thread via pipe.\n+bool FuseTest::CompareRequest(void* expected_mem, size_t expected_len,\n+ void* real_mem, size_t real_len) {\n+ if (expected_len != real_len) return false;\n+ return memcmp(expected_mem, real_mem, expected_len) == 0;\n+}\n+\n+// SetExpected is called by the testing main thread to set expected request-\n+// response pair of a single FUSE operation.\n+void FuseTest::SetExpected(struct iovec* iov_in, int iov_in_cnt,\n+ struct iovec* iov_out, int iov_out_cnt) {\n+ EXPECT_THAT(RetryEINTR(writev)(set_expected_[1], iov_in, iov_in_cnt),\n+ SyscallSucceedsWithValue(::testing::Gt(0)));\n+ WaitCompleted();\n+\n+ EXPECT_THAT(RetryEINTR(writev)(set_expected_[1], iov_out, iov_out_cnt),\n+ SyscallSucceedsWithValue(::testing::Gt(0)));\n+ WaitCompleted();\n+}\n+\n+// WaitCompleted waits for the FUSE server to finish its job and check if it\n+// completes without errors.\n+void FuseTest::WaitCompleted() {\n+ char success;\n+ EXPECT_THAT(RetryEINTR(read)(done_[0], &success, sizeof(success)),\n+ SyscallSucceedsWithValue(1));\n+}\n+\n+void FuseTest::MountFuse() {\n+ EXPECT_THAT(dev_fd_ = open(\"/dev/fuse\", O_RDWR), SyscallSucceeds());\n+\n+ std::string mount_opts = absl::StrFormat(\"fd=%d,%s\", dev_fd_, kMountOpts);\n+ EXPECT_THAT(mount(\"fuse\", kMountPoint, \"fuse\", MS_NODEV | MS_NOSUID,\n+ mount_opts.c_str()),\n+ SyscallSucceedsWithValue(0));\n+}\n+\n+void FuseTest::UnmountFuse() {\n+ EXPECT_THAT(umount(kMountPoint), SyscallSucceeds());\n+ // TODO(gvisor.dev/issue/3330): ensure the process is terminated successfully.\n+}\n+\n+// ConsumeFuseInit consumes the first FUSE request and returns the\n+// corresponding PosixError.\n+PosixError FuseTest::ConsumeFuseInit() {\n+ RETURN_ERROR_IF_SYSCALL_FAIL(\n+ RetryEINTR(read)(dev_fd_, buf_.data(), buf_.size()));\n+\n+ struct iovec iov_out[2];\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_init_out),\n+ .error = 0,\n+ .unique = 2,\n+ };\n+ // Returns an empty init out payload since this is just a test.\n+ struct fuse_init_out out_payload;\n+ iov_out[0].iov_len = sizeof(out_header);\n+ iov_out[0].iov_base = &out_header;\n+ iov_out[1].iov_len = sizeof(out_payload);\n+ iov_out[1].iov_base = &out_payload;\n+\n+ RETURN_ERROR_IF_SYSCALL_FAIL(RetryEINTR(writev)(dev_fd_, iov_out, 2));\n+ return NoError();\n+}\n+\n+// ReceiveExpected reads 1 pair of expected fuse request-response `iovec`s\n+// from pipe and save them into member variables of this testing instance.\n+void FuseTest::ReceiveExpected() {\n+ // Set expected fuse_in request.\n+ EXPECT_THAT(len_in_ = RetryEINTR(read)(set_expected_[0], mem_in_.data(),\n+ mem_in_.size()),\n+ SyscallSucceedsWithValue(::testing::Gt(0)));\n+ MarkDone(len_in_ > 0);\n+\n+ // Set expected fuse_out response.\n+ EXPECT_THAT(len_out_ = RetryEINTR(read)(set_expected_[0], mem_out_.data(),\n+ mem_out_.size()),\n+ SyscallSucceedsWithValue(::testing::Gt(0)));\n+ MarkDone(len_out_ > 0);\n+}\n+\n+// MarkDone writes 1 byte of success indicator through pipe.\n+void FuseTest::MarkDone(bool success) {\n+ char data = success ? 1 : 0;\n+ EXPECT_THAT(RetryEINTR(write)(done_[1], &data, sizeof(data)),\n+ SyscallSucceedsWithValue(1));\n+}\n+\n+// FuseLoop is the implementation of the fake FUSE server. Read from /dev/fuse,\n+// compare the request by CompareRequest (use derived function if specified),\n+// and write the expected response to /dev/fuse.\n+void FuseTest::FuseLoop() {\n+ bool success = true;\n+ ssize_t len = 0;\n+ while (true) {\n+ ReceiveExpected();\n+\n+ EXPECT_THAT(len = RetryEINTR(read)(dev_fd_, buf_.data(), buf_.size()),\n+ SyscallSucceedsWithValue(len_in_));\n+ if (len != len_in_) success = false;\n+\n+ if (!CompareRequest(buf_.data(), len_in_, mem_in_.data(), len_in_)) {\n+ std::cerr << \"the FUSE request is not expected\" << std::endl;\n+ success = false;\n+ }\n+\n+ EXPECT_THAT(len = RetryEINTR(write)(dev_fd_, mem_out_.data(), len_out_),\n+ SyscallSucceedsWithValue(len_out_));\n+ if (len != len_out_) success = false;\n+ MarkDone(success);\n+ }\n+}\n+\n+// SetUpFuseServer creates 2 pipes. First is for testing client to send the\n+// expected request-response pair, and the other acts as a checkpoint for the\n+// FUSE server to notify the client that it can proceed.\n+void FuseTest::SetUpFuseServer() {\n+ ASSERT_THAT(pipe(set_expected_), SyscallSucceedsWithValue(0));\n+ ASSERT_THAT(pipe(done_), SyscallSucceedsWithValue(0));\n+\n+ switch (fork()) {\n+ case -1:\n+ GTEST_FAIL();\n+ return;\n+ case 0:\n+ break;\n+ default:\n+ ASSERT_THAT(close(set_expected_[0]), SyscallSucceedsWithValue(0));\n+ ASSERT_THAT(close(done_[1]), SyscallSucceedsWithValue(0));\n+ WaitCompleted();\n+ return;\n+ }\n+\n+ ASSERT_THAT(close(set_expected_[1]), SyscallSucceedsWithValue(0));\n+ ASSERT_THAT(close(done_[0]), SyscallSucceedsWithValue(0));\n+\n+ MarkDone(ConsumeFuseInit().ok());\n+\n+ FuseLoop();\n+ _exit(0);\n+}\n+\n+// GetPayloadSize is a helper function to get the number of bytes of a\n+// specific FUSE operation struct.\n+size_t FuseTest::GetPayloadSize(uint32_t opcode, bool in) {\n+ switch (opcode) {\n+ case FUSE_INIT:\n+ return in ? sizeof(struct fuse_init_in) : sizeof(struct fuse_init_out);\n+ default:\n+ break;\n+ }\n+ return 0;\n+}\n+\n+} // namespace testing\n+} // namespace gvisor\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/fuse/linux/fuse_base.h",
"diff": "+// Copyright 2020 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_FUSE_FUSE_BASE_H_\n+#define GVISOR_TEST_FUSE_FUSE_BASE_H_\n+\n+#include <linux/fuse.h>\n+#include <sys/uio.h>\n+\n+#include <vector>\n+\n+#include \"gmock/gmock.h\"\n+#include \"gtest/gtest.h\"\n+#include \"test/util/posix_error.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+constexpr char kMountPoint[] = \"/mnt\";\n+constexpr char kMountOpts[] = \"rootmode=755,user_id=0,group_id=0\";\n+\n+class FuseTest : public ::testing::Test {\n+ public:\n+ FuseTest() {\n+ buf_.resize(FUSE_MIN_READ_BUFFER);\n+ mem_in_.resize(FUSE_MIN_READ_BUFFER);\n+ mem_out_.resize(FUSE_MIN_READ_BUFFER);\n+ }\n+ void SetUp() override;\n+ void TearDown() override;\n+\n+ // CompareRequest is used by the FUSE server and should be implemented to\n+ // compare different FUSE operations. It compares the actual FUSE input\n+ // request with the expected one set by `SetExpected()`.\n+ virtual bool CompareRequest(void* expected_mem, size_t expected_len,\n+ void* real_mem, size_t real_len);\n+\n+ // SetExpected is called by the testing main thread. Writes a request-\n+ // response pair into FUSE server's member variables via pipe.\n+ void SetExpected(struct iovec* iov_in, int iov_in_cnt, struct iovec* iov_out,\n+ int iov_out_cnt);\n+\n+ // WaitCompleted waits for FUSE server to complete its processing. It\n+ // complains if the FUSE server responds failure during tests.\n+ void WaitCompleted();\n+\n+ private:\n+ void MountFuse();\n+ void UnmountFuse();\n+\n+ // ConsumeFuseInit is only used during FUSE server setup.\n+ PosixError ConsumeFuseInit();\n+\n+ // ReceiveExpected is the FUSE server side's corresponding code of\n+ // `SetExpected()`. Save the request-response pair into its memory.\n+ void ReceiveExpected();\n+\n+ // MarkDone is used by the FUSE server to tell testing main if it's OK to\n+ // proceed next command.\n+ void MarkDone(bool success);\n+\n+ // FuseLoop is where the FUSE server stay until it is terminated.\n+ void FuseLoop();\n+\n+ // SetUpFuseServer creates 2 pipes for communication and forks FUSE server.\n+ void SetUpFuseServer();\n+\n+ // GetPayloadSize is a helper function to get the number of bytes of a\n+ // specific FUSE operation struct.\n+ size_t GetPayloadSize(uint32_t opcode, bool in);\n+\n+ int dev_fd_;\n+ int set_expected_[2];\n+ int done_[2];\n+\n+ std::vector<char> buf_;\n+ std::vector<char> mem_in_;\n+ std::vector<char> mem_out_;\n+ ssize_t len_in_;\n+ ssize_t len_out_;\n+};\n+\n+} // namespace testing\n+} // namespace gvisor\n+\n+#endif // GVISOR_TEST_FUSE_FUSE_BASE_H_\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runner/defs.bzl",
"new_path": "test/runner/defs.bzl",
"diff": "@@ -201,7 +201,7 @@ def syscall_test(\nplatform = default_platform,\nuse_tmpfs = use_tmpfs,\nadd_uds_tree = add_uds_tree,\n- tags = platforms[default_platform] + vfs2_tags,\n+ tags = platforms[default_platform] + vfs2_tags + [\"fuse\"],\nvfs2 = True,\nfuse = True,\n)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add FUSE integration test
This commit adds an integration test framework for FUSE support. Please
refer to the test example and test/fuse/README.md for further details.
Fixes #3098 |
260,004 | 04.08.2020 16:25:15 | 25,200 | 00993130e5a9c05aaa88c5a860407b079093a024 | Use 1 fragmentation component per IP stack
This will help manage memory consumption by IP reassembly when
receiving IP fragments on multiple network endpoints. Previously,
each endpoint would cap memory consumption at 4MB, but with this
change, each IP stack will cap memory consumption at 4MB.
No behaviour changes. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -57,7 +57,6 @@ type endpoint struct {\nprefixLen int\nlinkEP stack.LinkEndpoint\ndispatcher stack.TransportDispatcher\n- fragmentation *fragmentation.Fragmentation\nprotocol *protocol\nstack *stack.Stack\n}\n@@ -70,7 +69,6 @@ func (p *protocol) NewEndpoint(nicID tcpip.NICID, addrWithPrefix tcpip.AddressWi\nprefixLen: addrWithPrefix.PrefixLen,\nlinkEP: linkEP,\ndispatcher: dispatcher,\n- fragmentation: fragmentation.NewFragmentation(fragmentblockSize, fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, fragmentation.DefaultReassembleTimeout),\nprotocol: p,\nstack: st,\n}\n@@ -442,7 +440,9 @@ func (e *endpoint) HandlePacket(r *stack.Route, pkt *stack.PacketBuffer) {\n}\nvar ready bool\nvar err error\n- pkt.Data, ready, err = e.fragmentation.Process(\n+ pkt.Data, ready, err = e.protocol.fragmentation.Process(\n+ // As per RFC 791 section 2.3, the identification value is unique\n+ // for a source-destination pair and protocol.\nfragmentation.FragmentID{\nSource: h.SourceAddress(),\nDestination: h.DestinationAddress(),\n@@ -484,6 +484,8 @@ type protocol struct {\n// uint8 portion of it is meaningful and it must be accessed\n// atomically.\ndefaultTTL uint32\n+\n+ fragmentation *fragmentation.Fragmentation\n}\n// Number returns the ipv4 protocol number.\n@@ -605,5 +607,10 @@ func NewProtocol() stack.NetworkProtocol {\n}\nhashIV := r[buckets]\n- return &protocol{ids: ids, hashIV: hashIV, defaultTTL: DefaultTTL}\n+ return &protocol{\n+ ids: ids,\n+ hashIV: hashIV,\n+ defaultTTL: DefaultTTL,\n+ fragmentation: fragmentation.NewFragmentation(fragmentblockSize, fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, fragmentation.DefaultReassembleTimeout),\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -51,7 +51,6 @@ type endpoint struct {\nlinkEP stack.LinkEndpoint\nlinkAddrCache stack.LinkAddressCache\ndispatcher stack.TransportDispatcher\n- fragmentation *fragmentation.Fragmentation\nprotocol *protocol\n}\n@@ -342,7 +341,7 @@ func (e *endpoint) HandlePacket(r *stack.Route, pkt *stack.PacketBuffer) {\nvar ready bool\n// Note that pkt doesn't have its transport header set after reassembly,\n// and won't until DeliverNetworkPacket sets it.\n- pkt.Data, ready, err = e.fragmentation.Process(\n+ pkt.Data, ready, err = e.protocol.fragmentation.Process(\n// IPv6 ignores the Protocol field since the ID only needs to be unique\n// across source-destination pairs, as per RFC 8200 section 4.5.\nfragmentation.FragmentID{\n@@ -446,6 +445,7 @@ type protocol struct {\n// uint8 portion of it is meaningful and it must be accessed\n// atomically.\ndefaultTTL uint32\n+ fragmentation *fragmentation.Fragmentation\n}\n// Number returns the ipv6 protocol number.\n@@ -478,7 +478,6 @@ func (p *protocol) NewEndpoint(nicID tcpip.NICID, addrWithPrefix tcpip.AddressWi\nlinkEP: linkEP,\nlinkAddrCache: linkAddrCache,\ndispatcher: dispatcher,\n- fragmentation: fragmentation.NewFragmentation(header.IPv6FragmentExtHdrFragmentOffsetBytesPerUnit, fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, fragmentation.DefaultReassembleTimeout),\nprotocol: p,\n}, nil\n}\n@@ -606,5 +605,8 @@ func calculateMTU(mtu uint32) uint32 {\n// NewProtocol returns an IPv6 network protocol.\nfunc NewProtocol() stack.NetworkProtocol {\n- return &protocol{defaultTTL: DefaultTTL}\n+ return &protocol{\n+ defaultTTL: DefaultTTL,\n+ fragmentation: fragmentation.NewFragmentation(header.IPv6FragmentExtHdrFragmentOffsetBytesPerUnit, fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, fragmentation.DefaultReassembleTimeout),\n+ }\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use 1 fragmentation component per IP stack
This will help manage memory consumption by IP reassembly when
receiving IP fragments on multiple network endpoints. Previously,
each endpoint would cap memory consumption at 4MB, but with this
change, each IP stack will cap memory consumption at 4MB.
No behaviour changes.
PiperOrigin-RevId: 324913904 |
259,975 | 04.08.2020 16:48:40 | 25,200 | be7079578e0907fd3f35f91e9716246c179e17e9 | Port sysbench benchmark. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/sysbench/Dockerfile",
"diff": "+FROM ubuntu:18.04\n+\n+RUN set -x \\\n+ && apt-get update \\\n+ && apt-get install -y \\\n+ sysbench \\\n+ && rm -rf /var/lib/apt/lists/*\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/benchmarks/base/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"base\",\n+ testonly = 1,\n+ srcs = [\"base.go\"],\n+ deps = [\"//test/benchmarks/harness\"],\n+)\n+\n+go_test(\n+ name = \"base_test\",\n+ size = \"small\",\n+ srcs = [\"sysbench_test.go\"],\n+ library = \":base\",\n+ tags = [\n+ # Requires docker and runsc to be configured before test runs.\n+ \"manual\",\n+ \"local\",\n+ ],\n+ deps = [\n+ \"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/tools\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/benchmarks/base/base.go",
"diff": "+// Copyright 2020 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 base holds base performance benchmarks.\n+package base\n+\n+import (\n+ \"os\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/test/benchmarks/harness\"\n+)\n+\n+var h harness.Harness\n+\n+// TestMain is the main method for package network.\n+func TestMain(m *testing.M) {\n+ h.Init()\n+ os.Exit(m.Run())\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/benchmarks/base/sysbench_test.go",
"diff": "+// Copyright 2020 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 base\n+\n+import (\n+ \"context\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/test/dockerutil\"\n+ \"gvisor.dev/gvisor/test/benchmarks/tools\"\n+)\n+\n+type testCase struct {\n+ name string\n+ test tools.Sysbench\n+}\n+\n+// BenchmarSysbench runs sysbench on the runtime.\n+func BenchmarkSysbench(b *testing.B) {\n+\n+ testCases := []testCase{\n+ testCase{\n+ name: \"CPU\",\n+ test: &tools.SysbenchCPU{\n+ Base: tools.SysbenchBase{\n+ Threads: 1,\n+ Time: 5,\n+ },\n+ MaxPrime: 50000,\n+ },\n+ },\n+ testCase{\n+ name: \"Memory\",\n+ test: &tools.SysbenchMemory{\n+ Base: tools.SysbenchBase{\n+ Threads: 1,\n+ },\n+ BlockSize: \"1M\",\n+ TotalSize: \"500G\",\n+ },\n+ },\n+ testCase{\n+ name: \"Mutex\",\n+ test: &tools.SysbenchMutex{\n+ Base: tools.SysbenchBase{\n+ Threads: 8,\n+ },\n+ Loops: 1,\n+ Locks: 10000000,\n+ Num: 4,\n+ },\n+ },\n+ }\n+\n+ machine, err := h.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+ b.Run(tc.name, func(b *testing.B) {\n+\n+ ctx := context.Background()\n+ sysbench := machine.GetContainer(ctx, b)\n+ defer sysbench.CleanUp(ctx)\n+\n+ out, err := sysbench.Run(ctx, dockerutil.RunOpts{\n+ Image: \"benchmarks/sysbench\",\n+ }, tc.test.MakeCmd()...)\n+ if err != nil {\n+ b.Fatalf(\"failed to run sysbench: %v: logs:%s\", err, out)\n+ }\n+ tc.test.Report(b, out)\n+ })\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/database/BUILD",
"new_path": "test/benchmarks/database/BUILD",
"diff": "@@ -12,9 +12,7 @@ go_library(\ngo_test(\nname = \"database_test\",\nsize = \"enormous\",\n- srcs = [\n- \"redis_test.go\",\n- ],\n+ srcs = [\"redis_test.go\"],\nlibrary = \":database\",\ntags = [\n# Requires docker and runsc to be configured before test runs.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/tools/BUILD",
"new_path": "test/benchmarks/tools/BUILD",
"diff": "@@ -10,6 +10,7 @@ go_library(\n\"hey.go\",\n\"iperf.go\",\n\"redis.go\",\n+ \"sysbench.go\",\n\"tools.go\",\n],\nvisibility = [\"//:sandbox\"],\n@@ -24,6 +25,7 @@ go_test(\n\"hey_test.go\",\n\"iperf_test.go\",\n\"redis_test.go\",\n+ \"sysbench_test.go\",\n],\nlibrary = \":tools\",\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/tools/redis.go",
"new_path": "test/benchmarks/tools/redis.go",
"diff": "@@ -56,7 +56,6 @@ func (r *Redis) Report(b *testing.B, output string) {\nfunc (r *Redis) parseOperation(data string) (float64, error) {\nre := regexp.MustCompile(fmt.Sprintf(`\"%s( .*)?\",\"(\\d*\\.\\d*)\"`, r.Operation))\nmatch := re.FindStringSubmatch(data)\n- // If no match, simply don't add it to the result map.\nif len(match) < 3 {\nreturn 0.0, fmt.Errorf(\"could not find %s in %s\", r.Operation, data)\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/benchmarks/tools/sysbench.go",
"diff": "+// Copyright 2020 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+ \"strings\"\n+ \"testing\"\n+)\n+\n+var warmup = \"sysbench --threads=8 --memory-total-size=5G memory run > /dev/null &&\"\n+\n+// Sysbench represents a 'sysbench' command.\n+type Sysbench interface {\n+ MakeCmd() []string // Makes a sysbench command.\n+ flags() []string\n+ Report(*testing.B, string) // Reports results contained in string.\n+}\n+\n+// SysbenchBase is the top level struct for sysbench and holds top-level arguments\n+// for sysbench. See: 'sysbench --help'\n+type SysbenchBase struct {\n+ Threads int // number of Threads for the test.\n+ Time int // time limit for test in seconds.\n+}\n+\n+// baseFlags returns top level flags.\n+func (s *SysbenchBase) baseFlags() []string {\n+ var ret []string\n+ if s.Threads > 0 {\n+ ret = append(ret, fmt.Sprintf(\"--threads=%d\", s.Threads))\n+ }\n+ if s.Time > 0 {\n+ ret = append(ret, fmt.Sprintf(\"--time=%d\", s.Time))\n+ }\n+ return ret\n+}\n+\n+// SysbenchCPU is for 'sysbench [flags] cpu run' and holds CPU specific arguments.\n+type SysbenchCPU struct {\n+ Base SysbenchBase\n+ MaxPrime int // upper limit for primes generator [10000].\n+}\n+\n+// MakeCmd makes commands for SysbenchCPU.\n+func (s *SysbenchCPU) MakeCmd() []string {\n+ cmd := []string{warmup, \"sysbench\"}\n+ cmd = append(cmd, s.flags()...)\n+ cmd = append(cmd, \"cpu run\")\n+ return []string{\"sh\", \"-c\", strings.Join(cmd, \" \")}\n+}\n+\n+// flags makes flags for SysbenchCPU cmds.\n+func (s *SysbenchCPU) flags() []string {\n+ cmd := s.Base.baseFlags()\n+ if s.MaxPrime > 0 {\n+ return append(cmd, fmt.Sprintf(\"--cpu-max-prime=%d\", s.MaxPrime))\n+ }\n+ return cmd\n+}\n+\n+// Report reports the relevant metrics for SysbenchCPU.\n+func (s *SysbenchCPU) Report(b *testing.B, output string) {\n+ b.Helper()\n+ result, err := s.parseEvents(output)\n+ if err != nil {\n+ b.Fatalf(\"parsing CPU events from %s failed: %v\", output, err)\n+ }\n+ b.ReportMetric(result, \"cpu_events_per_second\")\n+}\n+\n+var cpuEventsPerSecondRE = regexp.MustCompile(`events per second:\\s*(\\d*.?\\d*)\\n`)\n+\n+// parseEvents parses cpu events per second.\n+func (s *SysbenchCPU) parseEvents(data string) (float64, error) {\n+ match := cpuEventsPerSecondRE.FindStringSubmatch(data)\n+ if len(match) < 2 {\n+ return 0.0, fmt.Errorf(\"could not find events per second: %s\", data)\n+ }\n+ return strconv.ParseFloat(match[1], 64)\n+}\n+\n+// SysbenchMemory is for 'sysbench [FLAGS] memory run' and holds Memory specific arguments.\n+type SysbenchMemory struct {\n+ Base SysbenchBase\n+ BlockSize string // size of test memory block [1K].\n+ TotalSize string // size of data to transfer [100G].\n+ Scope string // memory access scope {global, local} [global].\n+ HugeTLB bool // allocate memory from HugeTLB [off].\n+ OperationType string // type of memory ops {read, write, none} [write].\n+ AccessMode string // access mode {seq, rnd} [seq].\n+}\n+\n+// MakeCmd makes commands for SysbenchMemory.\n+func (s *SysbenchMemory) MakeCmd() []string {\n+ cmd := []string{warmup, \"sysbench\"}\n+ cmd = append(cmd, s.flags()...)\n+ cmd = append(cmd, \"memory run\")\n+ return []string{\"sh\", \"-c\", strings.Join(cmd, \" \")}\n+}\n+\n+// flags makes flags for SysbenchMemory cmds.\n+func (s *SysbenchMemory) flags() []string {\n+ cmd := s.Base.baseFlags()\n+ if s.BlockSize != \"\" {\n+ cmd = append(cmd, fmt.Sprintf(\"--memory-block-size=%s\", s.BlockSize))\n+ }\n+ if s.TotalSize != \"\" {\n+ cmd = append(cmd, fmt.Sprintf(\"--memory-total-size=%s\", s.TotalSize))\n+ }\n+ if s.Scope != \"\" {\n+ cmd = append(cmd, fmt.Sprintf(\"--memory-scope=%s\", s.Scope))\n+ }\n+ if s.HugeTLB {\n+ cmd = append(cmd, \"--memory-hugetlb=on\")\n+ }\n+ if s.OperationType != \"\" {\n+ cmd = append(cmd, fmt.Sprintf(\"--memory-oper=%s\", s.OperationType))\n+ }\n+ if s.AccessMode != \"\" {\n+ cmd = append(cmd, fmt.Sprintf(\"--memory-access-mode=%s\", s.AccessMode))\n+ }\n+ return cmd\n+}\n+\n+// Report reports the relevant metrics for SysbenchMemory.\n+func (s *SysbenchMemory) Report(b *testing.B, output string) {\n+ b.Helper()\n+ result, err := s.parseOperations(output)\n+ if err != nil {\n+ b.Fatalf(\"parsing result %s failed with err: %v\", output, err)\n+ }\n+ b.ReportMetric(result, \"operations_per_second\")\n+}\n+\n+var memoryOperationsRE = regexp.MustCompile(`Total\\soperations:\\s+\\d*\\s*\\((\\d*\\.\\d*)\\sper\\ssecond\\)`)\n+\n+// parseOperations parses memory operations per second form sysbench memory ouput.\n+func (s *SysbenchMemory) parseOperations(data string) (float64, error) {\n+ match := memoryOperationsRE.FindStringSubmatch(data)\n+ if len(match) < 2 {\n+ return 0.0, fmt.Errorf(\"couldn't find memory operations per second: %s\", data)\n+ }\n+ return strconv.ParseFloat(match[1], 64)\n+}\n+\n+// SysbenchMutex is for 'sysbench [FLAGS] mutex run' and holds Mutex specific arguments.\n+type SysbenchMutex struct {\n+ Base SysbenchBase\n+ Num int // total size of mutex array [4096].\n+ Locks int // number of mutex locks per thread [50K].\n+ Loops int // number of loops to do outside mutex lock [10K].\n+}\n+\n+// MakeCmd makes commands for SysbenchMutex.\n+func (s *SysbenchMutex) MakeCmd() []string {\n+ cmd := []string{warmup, \"sysbench\"}\n+ cmd = append(cmd, s.flags()...)\n+ cmd = append(cmd, \"mutex run\")\n+ return []string{\"sh\", \"-c\", strings.Join(cmd, \" \")}\n+}\n+\n+// flags makes flags for SysbenchMutex commands.\n+func (s *SysbenchMutex) flags() []string {\n+ var cmd []string\n+ cmd = append(cmd, s.Base.baseFlags()...)\n+ if s.Num > 0 {\n+ cmd = append(cmd, fmt.Sprintf(\"--mutex-num=%d\", s.Num))\n+ }\n+ if s.Locks > 0 {\n+ cmd = append(cmd, fmt.Sprintf(\"--mutex-locks=%d\", s.Locks))\n+ }\n+ if s.Loops > 0 {\n+ cmd = append(cmd, fmt.Sprintf(\"--mutex-loops=%d\", s.Loops))\n+ }\n+ return cmd\n+}\n+\n+// Report parses and reports relevant sysbench mutex metrics.\n+func (s *SysbenchMutex) Report(b *testing.B, output string) {\n+ b.Helper()\n+\n+ result, err := s.parseExecutionTime(output)\n+ if err != nil {\n+ b.Fatalf(\"parsing result %s failed with err: %v\", output, err)\n+ }\n+ b.ReportMetric(result, \"average_execution_time_secs\")\n+\n+ result, err = s.parseDeviation(output)\n+ if err != nil {\n+ b.Fatalf(\"parsing result %s failed with err: %v\", output, err)\n+ }\n+ b.ReportMetric(result, \"stdev_execution_time_secs\")\n+\n+ result, err = s.parseLatency(output)\n+ if err != nil {\n+ b.Fatalf(\"parsing result %s failed with err: %v\", output, err)\n+ }\n+ b.ReportMetric(result/1000, \"average_latency_secs\")\n+}\n+\n+var executionTimeRE = regexp.MustCompile(`execution time \\(avg/stddev\\):\\s*(\\d*.?\\d*)/(\\d*.?\\d*)`)\n+\n+// parseExecutionTime parses threads fairness average execution time from sysbench output.\n+func (s *SysbenchMutex) parseExecutionTime(data string) (float64, error) {\n+ match := executionTimeRE.FindStringSubmatch(data)\n+ if len(match) < 2 {\n+ return 0.0, fmt.Errorf(\"could not find execution time average: %s\", data)\n+ }\n+ return strconv.ParseFloat(match[1], 64)\n+}\n+\n+// parseDeviation parses threads fairness stddev time from sysbench output.\n+func (s *SysbenchMutex) parseDeviation(data string) (float64, error) {\n+ match := executionTimeRE.FindStringSubmatch(data)\n+ if len(match) < 3 {\n+ return 0.0, fmt.Errorf(\"could not find execution time deviation: %s\", data)\n+ }\n+ return strconv.ParseFloat(match[2], 64)\n+}\n+\n+var averageLatencyRE = regexp.MustCompile(`avg:[^\\n^\\d]*(\\d*\\.?\\d*)`)\n+\n+// parseLatency parses latency from sysbench output.\n+func (s *SysbenchMutex) parseLatency(data string) (float64, error) {\n+ match := averageLatencyRE.FindStringSubmatch(data)\n+ if len(match) < 2 {\n+ return 0.0, fmt.Errorf(\"could not find average latency: %s\", data)\n+ }\n+ return strconv.ParseFloat(match[1], 64)\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/benchmarks/tools/sysbench_test.go",
"diff": "+// Copyright 2020 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+ \"testing\"\n+)\n+\n+// TestSysbenchCpu tests parses on sample 'sysbench cpu' output.\n+func TestSysbenchCpu(t *testing.T) {\n+ sampleData := `\n+sysbench 1.0.11 (using system LuaJIT 2.1.0-beta3)\n+\n+Running the test with following options:\n+Number of threads: 8\n+Initializing random number generator from current time\n+\n+\n+Prime numbers limit: 10000\n+\n+Initializing worker threads...\n+\n+Threads started!\n+\n+CPU speed:\n+ events per second: 9093.38\n+\n+General statistics:\n+ total time: 10.0007s\n+ total number of events: 90949\n+\n+Latency (ms):\n+ min: 0.64\n+ avg: 0.88\n+ max: 24.65\n+ 95th percentile: 1.55\n+ sum: 79936.91\n+\n+Threads fairness:\n+ events (avg/stddev): 11368.6250/831.38\n+ execution time (avg/stddev): 9.9921/0.01\n+`\n+ sysbench := SysbenchCPU{}\n+ want := 9093.38\n+ if got, err := sysbench.parseEvents(sampleData); err != nil {\n+ t.Fatalf(\"parse cpu events failed: %v\", err)\n+ } else if want != got {\n+ t.Fatalf(\"got: %f want: %f\", got, want)\n+ }\n+}\n+\n+// TestSysbenchMemory tests parsers on sample 'sysbench memory' output.\n+func TestSysbenchMemory(t *testing.T) {\n+ sampleData := `\n+sysbench 1.0.11 (using system LuaJIT 2.1.0-beta3)\n+\n+Running the test with following options:\n+Number of threads: 8\n+Initializing random number generator from current time\n+\n+\n+Running memory speed test with the following options:\n+ block size: 1KiB\n+ total size: 102400MiB\n+ operation: write\n+ scope: global\n+\n+Initializing worker threads...\n+\n+Threads started!\n+\n+Total operations: 47999046 (9597428.64 per second)\n+\n+46874.07 MiB transferred (9372.49 MiB/sec)\n+\n+\n+General statistics:\n+ total time: 5.0001s\n+ total number of events: 47999046\n+\n+Latency (ms):\n+ min: 0.00\n+ avg: 0.00\n+ max: 0.21\n+ 95th percentile: 0.00\n+ sum: 33165.91\n+\n+Threads fairness:\n+ events (avg/stddev): 5999880.7500/111242.52\n+ execution time (avg/stddev): 4.1457/0.09\n+`\n+ sysbench := SysbenchMemory{}\n+ want := 9597428.64\n+ if got, err := sysbench.parseOperations(sampleData); err != nil {\n+ t.Fatalf(\"parse memory ops failed: %v\", err)\n+ } else if want != got {\n+ t.Fatalf(\"got: %f want: %f\", got, want)\n+ }\n+}\n+\n+// TestSysbenchMutex tests parsers on sample 'sysbench mutex' output.\n+func TestSysbenchMutex(t *testing.T) {\n+ sampleData := `\n+sysbench 1.0.11 (using system LuaJIT 2.1.0-beta3)\n+\n+The 'mutex' test requires a command argument. See 'sysbench mutex help'\n+root@ec078132e294:/# sysbench mutex --threads=8 run\n+sysbench 1.0.11 (using system LuaJIT 2.1.0-beta3)\n+\n+Running the test with following options:\n+Number of threads: 8\n+Initializing random number generator from current time\n+\n+\n+Initializing worker threads...\n+\n+Threads started!\n+\n+\n+General statistics:\n+ total time: 0.2320s\n+ total number of events: 8\n+\n+Latency (ms):\n+ min: 152.35\n+ avg: 192.48\n+ max: 231.41\n+ 95th percentile: 231.53\n+ sum: 1539.83\n+\n+Threads fairness:\n+ events (avg/stddev): 1.0000/0.00\n+ execution time (avg/stddev): 0.1925/0.04\n+`\n+\n+ sysbench := SysbenchMutex{}\n+ want := .1925\n+ if got, err := sysbench.parseExecutionTime(sampleData); err != nil {\n+ t.Fatalf(\"parse mutex time failed: %v\", err)\n+ } else if want != got {\n+ t.Fatalf(\"got: %f want: %f\", got, want)\n+ }\n+\n+ want = 0.04\n+ if got, err := sysbench.parseDeviation(sampleData); err != nil {\n+ t.Fatalf(\"parse mutex deviation failed: %v\", err)\n+ } else if want != got {\n+ t.Fatalf(\"got: %f want: %f\", got, want)\n+ }\n+\n+ want = 192.48\n+ if got, err := sysbench.parseLatency(sampleData); err != nil {\n+ t.Fatalf(\"parse mutex time failed: %v\", err)\n+ } else if want != got {\n+ t.Fatalf(\"got: %f want: %f\", got, want)\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Port sysbench benchmark.
PiperOrigin-RevId: 324918229 |
259,907 | 04.08.2020 17:18:48 | 25,200 | 338f96b36c778748ff27f5ae73cc73b222c5a90e | [runtime tests] Exclude flaky tests. | [
{
"change_type": "MODIFY",
"old_path": "test/runtimes/exclude_nodejs12.4.0.csv",
"new_path": "test/runtimes/exclude_nodejs12.4.0.csv",
"diff": "@@ -16,8 +16,11 @@ parallel/test-http-writable-true-after-close.js,,Flaky - Mismatched <anonymous>\nparallel/test-os.js,b/63997097,\nparallel/test-process-uid-gid.js,,\nparallel/test-tls-cli-min-version-1.0.js,,Flaky - EADDRINUSE\n+parallel/test-tls-cli-min-version-1.1.js,,Flaky - EADDRINUSE\n+parallel/test-tls-cli-min-version-1.2.js,,Flaky - EADDRINUSE\nparallel/test-tls-cli-min-version-1.3.js,,Flaky - EADDRINUSE\n-parallel/test-tls-cli-max-version-1.2,,Flaky - EADDRINUSE\n+parallel/test-tls-cli-max-version-1.2.js,,Flaky - EADDRINUSE\n+parallel/test-tls-cli-max-version-1.3.js,,Flaky - EADDRINUSE\nparallel/test-tls-min-max-version.js,,Flaky - EADDRINUSE\npseudo-tty/test-assert-colors.js,b/162801321,\npseudo-tty/test-assert-no-color.js,b/162801321,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runtimes/exclude_php7.3.6.csv",
"new_path": "test/runtimes/exclude_php7.3.6.csv",
"diff": "@@ -8,6 +8,7 @@ ext/mbstring/tests/bug77165.phpt,,\next/mbstring/tests/bug77454.phpt,,\next/mbstring/tests/mb_convert_encoding_leak.phpt,,\next/mbstring/tests/mb_strrpos_encoding_3rd_param.phpt,,\n+ext/session/tests/session_module_name_variation4.phpt,,Flaky\next/session/tests/session_set_save_handler_class_018.phpt,,\next/session/tests/session_set_save_handler_iface_003.phpt,,\next/session/tests/session_set_save_handler_variation4.phpt,,\n@@ -25,6 +26,7 @@ ext/standard/tests/file/symlink_link_linkinfo_is_link_variation8.phpt,,\next/standard/tests/general_functions/escapeshellarg_bug71270.phpt,,\next/standard/tests/general_functions/escapeshellcmd_bug71270.phpt,,\next/standard/tests/network/bug20134.phpt,,\n+ext/standard/tests/streams/proc_open_bug69900.phpt,,Flaky\next/standard/tests/streams/stream_socket_sendto.phpt,,\next/standard/tests/strings/007.phpt,,\nsapi/cli/tests/upload_2G.phpt,,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runtimes/exclude_python3.7.3.csv",
"new_path": "test/runtimes/exclude_python3.7.3.csv",
"diff": "@@ -20,6 +20,7 @@ test_readline,b/76157709,out of pty devices\ntest_resource,b/76174079,\ntest_selectors,b/76116849,OSError not raised with epoll\ntest_smtplib,b/76031995,SO_REUSEADDR and unclosed sockets\n+test_signal,,Flaky - signal: alarm clock\ntest_socket,b/75983380,\ntest_ssl,b/76031995,SO_REUSEADDR\ntest_subprocess,,\n"
}
] | Go | Apache License 2.0 | google/gvisor | [runtime tests] Exclude flaky tests.
PiperOrigin-RevId: 324923599 |
259,992 | 04.08.2020 19:04:12 | 25,200 | 102735bfb45820dd840df14827b42744da77c9a0 | Inline gofer.regularFileFD.pwriteLocked
Go compiler barely inlines anything, so inline by hand
pwriteLocked since it's called from a single place. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/regular_file.go",
"new_path": "pkg/sentry/fsimpl/gofer/regular_file.go",
"diff": "@@ -184,6 +184,7 @@ func (fd *regularFileFD) pwrite(ctx context.Context, src usermem.IOSequence, off\nd.metadataMu.Lock()\ndefer d.metadataMu.Unlock()\n+\n// Set offset to file size if the fd was opened with O_APPEND.\nif fd.vfsfd.StatusFlags()&linux.O_APPEND != 0 {\n// Holding d.metadataMu is sufficient for reading d.size.\n@@ -194,33 +195,59 @@ func (fd *regularFileFD) pwrite(ctx context.Context, src usermem.IOSequence, off\nreturn 0, offset, err\n}\nsrc = src.TakeFirst64(limit)\n- n, err := fd.pwriteLocked(ctx, src, offset, opts)\n- return n, offset + n, err\n-}\n-// Preconditions: fd.dentry().metatdataMu must be locked.\n-func (fd *regularFileFD) pwriteLocked(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\n- d := fd.dentry()\nif d.fs.opts.interop != InteropModeShared {\n// Compare Linux's mm/filemap.c:__generic_file_write_iter() =>\n// file_update_time(). This is d.touchCMtime(), but without locking\n// d.metadataMu (recursively).\nd.touchCMtimeLocked()\n}\n+\n+ rw := getDentryReadWriter(ctx, d, offset)\n+ defer putDentryReadWriter(rw)\n+\nif fd.vfsfd.StatusFlags()&linux.O_DIRECT != 0 {\n+ if err := fd.writeCache(ctx, d, offset, src); err != nil {\n+ return 0, offset, err\n+ }\n+\n+ // Require the write to go to the remote file.\n+ rw.direct = true\n+ }\n+\n+ n, err := src.CopyInTo(ctx, rw)\n+ if err != nil {\n+ return n, offset, err\n+ }\n+ if n > 0 && fd.vfsfd.StatusFlags()&(linux.O_DSYNC|linux.O_SYNC) != 0 {\n+ // Write dirty cached pages touched by the write back to the remote file.\n+ if err := d.writeback(ctx, offset, src.NumBytes()); err != nil {\n+ return n, offset, err\n+ }\n+ // Request the remote filesystem to sync the remote file.\n+ if err := d.handle.sync(ctx); err != nil {\n+ return n, offset, err\n+ }\n+ }\n+ return n, offset + n, nil\n+}\n+\n+func (fd *regularFileFD) writeCache(ctx context.Context, d *dentry, offset int64, src usermem.IOSequence) error {\n// Write dirty cached pages that will be touched by the write back to\n// the remote file.\nif err := d.writeback(ctx, offset, src.NumBytes()); err != nil {\n- return 0, err\n+ return err\n}\n+\n// Remove touched pages from the cache.\npgstart := usermem.PageRoundDown(uint64(offset))\npgend, ok := usermem.PageRoundUp(uint64(offset + src.NumBytes()))\nif !ok {\n- return 0, syserror.EINVAL\n+ return syserror.EINVAL\n}\nmr := memmap.MappableRange{pgstart, pgend}\nvar freed []memmap.FileRange\n+\nd.dataMu.Lock()\ncseg := d.cache.LowerBoundSegment(mr.Start)\nfor cseg.Ok() && cseg.Start() < mr.End {\n@@ -229,35 +256,18 @@ func (fd *regularFileFD) pwriteLocked(ctx context.Context, src usermem.IOSequenc\ncseg = d.cache.Remove(cseg).NextSegment()\n}\nd.dataMu.Unlock()\n+\n// Invalidate mappings of removed pages.\nd.mapsMu.Lock()\nd.mappings.Invalidate(mr, memmap.InvalidateOpts{})\nd.mapsMu.Unlock()\n+\n// Finally free pages removed from the cache.\nmf := d.fs.mfp.MemoryFile()\nfor _, freedFR := range freed {\nmf.DecRef(freedFR)\n}\n- }\n- rw := getDentryReadWriter(ctx, d, offset)\n- if fd.vfsfd.StatusFlags()&linux.O_DIRECT != 0 {\n- // Require the write to go to the remote file.\n- rw.direct = true\n- }\n- n, err := src.CopyInTo(ctx, rw)\n- putDentryReadWriter(rw)\n- if n != 0 && fd.vfsfd.StatusFlags()&(linux.O_DSYNC|linux.O_SYNC) != 0 {\n- // Write dirty cached pages touched by the write back to the remote\n- // file.\n- if err := d.writeback(ctx, offset, src.NumBytes()); err != nil {\n- return 0, err\n- }\n- // Request the remote filesystem to sync the remote file.\n- if err := d.handle.file.fsync(ctx); err != nil {\n- return 0, err\n- }\n- }\n- return n, err\n+ return nil\n}\n// Write implements vfs.FileDescriptionImpl.Write.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Inline gofer.regularFileFD.pwriteLocked
Go compiler barely inlines anything, so inline by hand
pwriteLocked since it's called from a single place.
PiperOrigin-RevId: 324937734 |
259,860 | 04.08.2020 19:10:28 | 25,200 | 87ee3898f78cb7d520281ead600036052d6a2049 | Handle EOF in vfs2 sendfile.
Discovered by syzkaller. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/splice.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/splice.go",
"diff": "@@ -347,6 +347,11 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n} else {\nspliceN, err = inFile.Read(t, outPipeFD.IOSequence(count), vfs.ReadOptions{})\n}\n+ if spliceN == 0 && err == io.EOF {\n+ // We reached the end of the file. Eat the error and exit the loop.\n+ err = nil\n+ break\n+ }\nn += spliceN\nif err == syserror.ErrWouldBlock && !nonBlock {\nerr = dw.waitForBoth(t)\n@@ -367,8 +372,7 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\nreadN, err = inFile.Read(t, usermem.BytesIOSequence(buf), vfs.ReadOptions{})\n}\nif readN == 0 && err == io.EOF {\n- // We reached the end of the file. Eat the\n- // error and exit the loop.\n+ // We reached the end of the file. Eat the error and exit the loop.\nerr = nil\nbreak\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Handle EOF in vfs2 sendfile.
Discovered by syzkaller.
PiperOrigin-RevId: 324938438 |
259,858 | 04.08.2020 20:49:00 | 25,200 | c5f5806fe69e8d4be99341318f20ce0acfd7be2a | Enable "make packetimpact-tests" to work.
This required minor fixes to the bazel wrapper. The "dut_platform" is
also changed to "native" to line-up with the system call tests and
remove the hard-coded "linux" and "netstack" strings. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -185,7 +185,6 @@ swgso-tests: load-basic-images\n@$(call submake,install-test-runtime RUNTIME=\"swgso\" ARGS=\"--software-gso=true --gso=false\")\n@$(call submake,test-runtime RUNTIME=\"swgso\" TARGETS=\"$(INTEGRATION_TARGETS)\")\n.PHONY: swgso-tests\n-\nhostnet-tests: load-basic-images\n@$(call submake,install-test-runtime RUNTIME=\"hostnet\" ARGS=\"--network=host\")\n@$(call submake,test-runtime RUNTIME=\"hostnet\" OPTIONS=\"--test_arg=-checkpoint=false\" TARGETS=\"$(INTEGRATION_TARGETS)\")\n@@ -211,8 +210,9 @@ packetdrill-tests: load-packetdrill\n.PHONY: packetdrill-tests\npacketimpact-tests: load-packetimpact\n+ @sudo modprobe iptable_filter ip6table_filter\n@$(call submake,install-test-runtime RUNTIME=\"packetimpact\")\n- @$(call submake,test-runtime RUNTIME=\"packetimpact\" TARGETS=\"$(shell $(MAKE) query TARGETS='attr(tags, packetimpact, tests(//...))')\")\n+ @$(call submake,test-runtime OPTIONS=\"--jobs=HOST_CPUS*3 --local_test_jobs=HOST_CPUS*3\" RUNTIME=\"packetimpact\" TARGETS=\"$(shell $(MAKE) query TARGETS='attr(tags, packetimpact, tests(//...))')\")\n.PHONY: packetimpact-tests\nroot-tests: load-basic-images\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/runner/defs.bzl",
"new_path": "test/packetimpact/runner/defs.bzl",
"diff": "@@ -61,12 +61,12 @@ PACKETIMPACT_TAGS = [\n\"packetimpact\",\n]\n-def packetimpact_linux_test(\n+def packetimpact_native_test(\nname,\ntestbench_binary,\nexpect_failure = False,\n**kwargs):\n- \"\"\"Add a packetimpact test on linux.\n+ \"\"\"Add a native packetimpact test.\nArgs:\nname: name of the test\n@@ -76,9 +76,9 @@ def packetimpact_linux_test(\n\"\"\"\nexpect_failure_flag = [\"--expect_failure\"] if expect_failure else []\n_packetimpact_test(\n- name = name + \"_linux_test\",\n+ name = name + \"_native_test\",\ntestbench_binary = testbench_binary,\n- flags = [\"--dut_platform\", \"linux\"] + expect_failure_flag,\n+ flags = [\"--native\"] + expect_failure_flag,\ntags = PACKETIMPACT_TAGS,\n**kwargs\n)\n@@ -102,21 +102,21 @@ def packetimpact_netstack_test(\n_packetimpact_test(\nname = name + \"_netstack_test\",\ntestbench_binary = testbench_binary,\n- # This is the default runtime unless\n- # \"--test_arg=--runtime=OTHER_RUNTIME\" is used to override the value.\n- flags = [\"--dut_platform\", \"netstack\", \"--runtime=runsc-d\"] + expect_failure_flag,\n+ # Note that a distinct runtime must be provided in the form\n+ # --test_arg=--runtime=other when invoking bazel.\n+ flags = expect_failure_flag,\ntags = PACKETIMPACT_TAGS,\n**kwargs\n)\n-def packetimpact_go_test(name, size = \"small\", pure = True, expect_linux_failure = False, expect_netstack_failure = False, **kwargs):\n+def packetimpact_go_test(name, size = \"small\", pure = True, expect_native_failure = False, expect_netstack_failure = False, **kwargs):\n\"\"\"Add packetimpact tests written in go.\nArgs:\nname: name of the test\nsize: size of the test\npure: make a static go binary\n- expect_linux_failure: the test must fail for Linux\n+ expect_native_failure: the test must fail natively\nexpect_netstack_failure: the test must fail for Netstack\n**kwargs: all the other args, forwarded to go_test\n\"\"\"\n@@ -131,9 +131,9 @@ def packetimpact_go_test(name, size = \"small\", pure = True, expect_linux_failure\n],\n**kwargs\n)\n- packetimpact_linux_test(\n+ packetimpact_native_test(\nname = name,\n- expect_failure = expect_linux_failure,\n+ expect_failure = expect_native_failure,\ntestbench_binary = testbench_binary,\n)\npacketimpact_netstack_test(\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/runner/packetimpact_test.go",
"new_path": "test/packetimpact/runner/packetimpact_test.go",
"diff": "@@ -50,7 +50,7 @@ func (l *stringList) Set(value string) error {\n}\nvar (\n- dutPlatform = flag.String(\"dut_platform\", \"\", \"either \\\"linux\\\" or \\\"netstack\\\"\")\n+ native = flag.Bool(\"native\", false, \"whether the test should be run natively\")\ntestbenchBinary = flag.String(\"testbench_binary\", \"\", \"path to the testbench binary\")\ntshark = flag.Bool(\"tshark\", false, \"use more verbose tshark in logs instead of tcpdump\")\nextraTestArgs = stringList{}\n@@ -84,17 +84,9 @@ func (l logger) Logf(format string, args ...interface{}) {\nfunc TestOne(t *testing.T) {\nflag.Var(&extraTestArgs, \"extra_test_arg\", \"extra arguments to pass to the testbench\")\nflag.Parse()\n- if *dutPlatform != \"linux\" && *dutPlatform != \"netstack\" {\n- t.Fatal(\"--dut_platform should be either linux or netstack\")\n- }\nif *testbenchBinary == \"\" {\nt.Fatal(\"--testbench_binary is missing\")\n}\n- if *dutPlatform == \"netstack\" {\n- if _, err := dockerutil.RuntimePath(); err != nil {\n- t.Fatal(\"--runtime is missing or invalid with --dut_platform=netstack:\", err)\n- }\n- }\ndockerutil.EnsureSupportedDockerVersion()\nctx := context.Background()\n@@ -140,9 +132,11 @@ func TestOne(t *testing.T) {\nconst testOutputDir = \"/tmp/testoutput\"\n// Create the Docker container for the DUT.\n- dut := dockerutil.MakeContainer(ctx, logger(\"dut\"))\n- if *dutPlatform == \"linux\" {\n+ var dut *dockerutil.Container\n+ if *native {\ndut = dockerutil.MakeNativeContainer(ctx, logger(\"dut\"))\n+ } else {\n+ dut = dockerutil.MakeContainer(ctx, logger(\"dut\"))\n}\nrunOpts := dockerutil.RunOpts{\n@@ -307,7 +301,7 @@ func TestOne(t *testing.T) {\n\"--remote_mac\", remoteMAC.String(),\n\"--remote_interface_id\", fmt.Sprintf(\"%d\", dutDeviceInfo.ID),\n\"--device\", testNetDev,\n- \"--dut_type\", *dutPlatform,\n+ fmt.Sprintf(\"--native=%t\", *native),\n)\ntestbenchLogs, err := testbench.Exec(ctx, dockerutil.ExecOpts{}, testArgs...)\nif (err != nil) != *expectFailure {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/testbench.go",
"new_path": "test/packetimpact/testbench/testbench.go",
"diff": "@@ -27,8 +27,8 @@ import (\n)\nvar (\n- // DUTType is the type of device under test.\n- DUTType = \"\"\n+ // Native indicates that the test is being run natively.\n+ Native = false\n// Device is the local device on the test network.\nDevice = \"\"\n@@ -81,7 +81,7 @@ func RegisterFlags(fs *flag.FlagSet) {\nfs.StringVar(&RemoteIPv6, \"remote_ipv6\", RemoteIPv6, \"remote IPv6 address for test packets\")\nfs.StringVar(&RemoteMAC, \"remote_mac\", RemoteMAC, \"remote mac address for test packets\")\nfs.StringVar(&Device, \"device\", Device, \"local device for test packets\")\n- fs.StringVar(&DUTType, \"dut_type\", DUTType, \"type of device under test\")\n+ fs.BoolVar(&Native, \"native\", Native, \"whether the test is running natively\")\nfs.Uint64Var(&RemoteInterfaceID, \"remote_interface_id\", RemoteInterfaceID, \"remote interface ID for test packets\")\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/tcp_reordering_test.go",
"new_path": "test/packetimpact/tests/tcp_reordering_test.go",
"diff": "@@ -54,13 +54,13 @@ func TestReorderingWindow(t *testing.T) {\nacceptFd, _ := dut.Accept(t, listenFd)\ndefer dut.Close(t, acceptFd)\n- if tb.DUTType == \"linux\" {\n+ if tb.Native {\n// Linux has changed its handling of reordering, force the old behavior.\ndut.SetSockOpt(t, acceptFd, unix.IPPROTO_TCP, unix.TCP_CONGESTION, []byte(\"reno\"))\n}\npls := dut.GetSockOptInt(t, acceptFd, unix.IPPROTO_TCP, unix.TCP_MAXSEG)\n- if tb.DUTType == \"netstack\" {\n+ if !tb.Native {\n// netstack does not impliment TCP_MAXSEG correctly. Fake it\n// here. Netstack uses the max SACK size which is 32. The MSS\n// option is 8 bytes, making the total 36 bytes.\n@@ -141,7 +141,7 @@ func TestReorderingWindow(t *testing.T) {\n}\n}\n- if tb.DUTType == \"netstack\" {\n+ if !tb.Native {\n// The window should now be halved, so we should receive any\n// more, even if we send them.\ndut.Send(t, acceptFd, payload, 0)\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazel.mk",
"new_path": "tools/bazel.mk",
"diff": "@@ -33,8 +33,8 @@ GCLOUD_CONFIG := $(shell readlink -m ~/.config/gcloud/)\nDOCKER_SOCKET := /var/run/docker.sock\n# Bazel flags.\n-OPTIONS += --test_output=errors --keep_going --verbose_failures=true\nBAZEL := bazel $(STARTUP_OPTIONS)\n+OPTIONS += --color=no --curses=no\n# Basic options.\nUID := $(shell id -u ${USER})\n@@ -143,12 +143,13 @@ bazel-server: ## Ensures that the server exists. Used as an internal target.\n@docker exec $(FULL_DOCKER_EXEC_OPTIONS) $(DOCKER_NAME) true || $(MAKE) bazel-server-start\n.PHONY: bazel-server\n-build_cmd = docker exec $(FULL_DOCKER_EXEC_OPTIONS) $(DOCKER_NAME) sh -o pipefail -c '$(BAZEL) build $(OPTIONS) $(TARGETS)'\n+build_cmd = docker exec $(FULL_DOCKER_EXEC_OPTIONS) $(DOCKER_NAME) sh -o pipefail -c '$(BAZEL) build $(OPTIONS) \"$(TARGETS)\"'\nbuild_paths = $(build_cmd) 2>&1 \\\n| tee /proc/self/fd/2 \\\n| grep -E \"^ bazel-bin/\" \\\n- | awk \"{print $$1;}\" \\\n+ | tr -d '\\r' \\\n+ | awk '{$$1=$$1};1' \\\n| xargs -n 1 -I {} sh -c \"$(1)\"\nbuild: bazel-server\n@@ -169,10 +170,12 @@ sudo: bazel-server\n@$(call build_paths,sudo -E {} $(ARGS))\n.PHONY: sudo\n+test: OPTIONS += --test_output=errors --keep_going --verbose_failures=true\ntest: bazel-server\n@docker exec $(FULL_DOCKER_EXEC_OPTIONS) $(DOCKER_NAME) $(BAZEL) test $(OPTIONS) $(TARGETS)\n.PHONY: test\n-query: bazel-server\n- @docker exec $(FULL_DOCKER_EXEC_OPTIONS) $(DOCKER_NAME) $(BAZEL) query $(OPTIONS) '$(TARGETS)'\n+query:\n+ @$(MAKE) bazel-server >&2 # If we need to start, ensure stdout is not polluted.\n+ @docker exec $(FULL_DOCKER_EXEC_OPTIONS) $(DOCKER_NAME) sh -o pipefail -c '$(BAZEL) query $(OPTIONS) \"$(TARGETS)\" 2>/dev/null'\n.PHONY: query\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable "make packetimpact-tests" to work.
This required minor fixes to the bazel wrapper. The "dut_platform" is
also changed to "native" to line-up with the system call tests and
remove the hard-coded "linux" and "netstack" strings. |
259,896 | 04.08.2020 20:57:28 | 25,200 | 0e6f7a12c29efa52581c38ca30637b133556a6cf | Update variables for implementation of RACK in TCP
RACK (Recent Acknowledgement) is a new loss detection
algorithm in TCP. These are the fields which should be
stored on connections to implement RACK algorithm. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -73,6 +73,16 @@ type TCPCubicState struct {\nWEst float64\n}\n+// TCPRACKState is used to hold a copy of the internal RACK state when the\n+// TCPProbeFunc is invoked.\n+type TCPRACKState struct {\n+ XmitTime time.Time\n+ EndSequence seqnum.Value\n+ FACK seqnum.Value\n+ RTT time.Duration\n+ Reord bool\n+}\n+\n// TCPEndpointID is the unique 4 tuple that identifies a given endpoint.\ntype TCPEndpointID struct {\n// LocalPort is the local port associated with the endpoint.\n@@ -212,6 +222,9 @@ type TCPSenderState struct {\n// Cubic holds the state related to CUBIC congestion control.\nCubic TCPCubicState\n+\n+ // RACKState holds the state related to RACK loss detection algorithm.\n+ RACKState TCPRACKState\n}\n// TCPSACKInfo holds TCP SACK related information for a given TCP endpoint.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/BUILD",
"new_path": "pkg/tcpip/transport/tcp/BUILD",
"diff": "@@ -40,6 +40,8 @@ go_library(\n\"endpoint_state.go\",\n\"forwarder.go\",\n\"protocol.go\",\n+ \"rack.go\",\n+ \"rack_state.go\",\n\"rcv.go\",\n\"rcv_state.go\",\n\"reno.go\",\n@@ -83,6 +85,7 @@ go_test(\n\"dual_stack_test.go\",\n\"sack_scoreboard_test.go\",\n\"tcp_noracedetector_test.go\",\n+ \"tcp_rack_test.go\",\n\"tcp_sack_test.go\",\n\"tcp_test.go\",\n\"tcp_timestamp_test.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/accept.go",
"new_path": "pkg/tcpip/transport/tcp/accept.go",
"diff": "@@ -521,7 +521,7 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) {\nsynOpts := header.TCPSynOptions{\nWS: -1,\nTS: opts.TS,\n- TSVal: tcpTimeStamp(timeStampOffset()),\n+ TSVal: tcpTimeStamp(time.Now(), timeStampOffset()),\nTSEcr: opts.TSVal,\nMSS: mssForRoute(&s.route),\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -1166,13 +1166,18 @@ func (e *endpoint) handleSegments(fastPath bool) *tcpip.Error {\nreturn nil\n}\n-// handleSegment handles a given segment and notifies the worker goroutine if\n-// if the connection should be terminated.\n-func (e *endpoint) handleSegment(s *segment) (cont bool, err *tcpip.Error) {\n- // Invoke the tcp probe if installed.\n+func (e *endpoint) probeSegment() {\nif e.probe != nil {\ne.probe(e.completeState())\n}\n+}\n+\n+// handleSegment handles a given segment and notifies the worker goroutine if\n+// if the connection should be terminated.\n+func (e *endpoint) handleSegment(s *segment) (cont bool, err *tcpip.Error) {\n+ // Invoke the tcp probe if installed. The tcp probe function will update\n+ // the TCPEndpointState after the segment is processed.\n+ defer e.probeSegment()\nif s.flagIsSet(header.TCPFlagRst) {\nif ok, err := e.handleReset(s); !ok {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -2692,15 +2692,14 @@ func (e *endpoint) maybeEnableTimestamp(synOpts *header.TCPSynOptions) {\n// timestamp returns the timestamp value to be used in the TSVal field of the\n// timestamp option for outgoing TCP segments for a given endpoint.\nfunc (e *endpoint) timestamp() uint32 {\n- return tcpTimeStamp(e.tsOffset)\n+ return tcpTimeStamp(time.Now(), e.tsOffset)\n}\n// tcpTimeStamp returns a timestamp offset by the provided offset. This is\n// not inlined above as it's used when SYN cookies are in use and endpoint\n// is not created at the time when the SYN cookie is sent.\n-func tcpTimeStamp(offset uint32) uint32 {\n- now := time.Now()\n- return uint32(now.Unix()*1000+int64(now.Nanosecond()/1e6)) + offset\n+func tcpTimeStamp(curTime time.Time, offset uint32) uint32 {\n+ return uint32(curTime.Unix()*1000+int64(curTime.Nanosecond()/1e6)) + offset\n}\n// timeStampOffset returns a randomized timestamp offset to be used when sending\n@@ -2843,6 +2842,14 @@ func (e *endpoint) completeState() stack.TCPEndpointState {\nWEst: cubic.wEst,\n}\n}\n+\n+ rc := e.snd.rc\n+ s.Sender.RACKState = stack.TCPRACKState{\n+ XmitTime: rc.xmitTime,\n+ EndSequence: rc.endSequence,\n+ FACK: rc.fack,\n+ RTT: rc.rtt,\n+ }\nreturn s\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/transport/tcp/rack.go",
"diff": "+// Copyright 2020 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 tcp\n+\n+import (\n+ \"time\"\n+\n+ \"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n+)\n+\n+// RACK is a loss detection algorithm used in TCP to detect packet loss and\n+// reordering using transmission timestamp of the packets instead of packet or\n+// sequence counts. To use RACK, SACK should be enabled on the connection.\n+\n+// rackControl stores the rack related fields.\n+// See: https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-6.1\n+//\n+// +stateify savable\n+type rackControl struct {\n+ // xmitTime is the latest transmission timestamp of rackControl.seg.\n+ xmitTime time.Time `state:\".(unixTime)\"`\n+\n+ // endSequence is the ending TCP sequence number of rackControl.seg.\n+ endSequence seqnum.Value\n+\n+ // fack is the highest selectively or cumulatively acknowledged\n+ // sequence.\n+ fack seqnum.Value\n+\n+ // rtt is the RTT of the most recently delivered packet on the\n+ // connection (either cumulatively acknowledged or selectively\n+ // acknowledged) that was not marked invalid as a possible spurious\n+ // retransmission.\n+ rtt time.Duration\n+}\n+\n+// Update will update the RACK related fields when an ACK has been received.\n+// See: https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-7.2\n+func (rc *rackControl) Update(seg *segment, ackSeg *segment, srtt time.Duration, offset uint32) {\n+ rtt := time.Now().Sub(seg.xmitTime)\n+\n+ // If the ACK is for a retransmitted packet, do not update if it is a\n+ // spurious inference which is determined by below checks:\n+ // 1. When Timestamping option is available, if the TSVal is less than the\n+ // transmit time of the most recent retransmitted packet.\n+ // 2. When RTT calculated for the packet is less than the smoothed RTT\n+ // for the connection.\n+ // See: https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-7.2\n+ // step 2\n+ if seg.xmitCount > 1 {\n+ if ackSeg.parsedOptions.TS && ackSeg.parsedOptions.TSEcr != 0 {\n+ if ackSeg.parsedOptions.TSEcr < tcpTimeStamp(seg.xmitTime, offset) {\n+ return\n+ }\n+ }\n+ if rtt < srtt {\n+ return\n+ }\n+ }\n+\n+ rc.rtt = rtt\n+ // Update rc.xmitTime and rc.endSequence to the transmit time and\n+ // ending sequence number of the packet which has been acknowledged\n+ // most recently.\n+ endSeq := seg.sequenceNumber.Add(seqnum.Size(seg.data.Size()))\n+ if rc.xmitTime.Before(seg.xmitTime) || (seg.xmitTime.Equal(rc.xmitTime) && rc.endSequence.LessThan(endSeq)) {\n+ rc.xmitTime = seg.xmitTime\n+ rc.endSequence = endSeq\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/transport/tcp/rack_state.go",
"diff": "+// Copyright 2020 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 tcp\n+\n+import (\n+ \"time\"\n+)\n+\n+// saveXmitTime is invoked by stateify.\n+func (rc *rackControl) saveXmitTime() unixTime {\n+ return unixTime{rc.xmitTime.Unix(), rc.xmitTime.UnixNano()}\n+}\n+\n+// loadXmitTime is invoked by stateify.\n+func (rc *rackControl) loadXmitTime(unix unixTime) {\n+ rc.xmitTime = time.Unix(unix.second, unix.nano)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/snd.go",
"new_path": "pkg/tcpip/transport/tcp/snd.go",
"diff": "@@ -191,6 +191,10 @@ type sender struct {\n// cc is the congestion control algorithm in use for this sender.\ncc congestionControl\n+\n+ // rc has the fields needed for implementing RACK loss detection\n+ // algorithm.\n+ rc rackControl\n}\n// rtt is a synchronization wrapper used to appease stateify. See the comment\n@@ -1272,21 +1276,21 @@ func (s *sender) checkDuplicateAck(seg *segment) (rtx bool) {\n// handleRcvdSegment is called when a segment is received; it is responsible for\n// updating the send-related state.\n-func (s *sender) handleRcvdSegment(seg *segment) {\n+func (s *sender) handleRcvdSegment(rcvdSeg *segment) {\n// Check if we can extract an RTT measurement from this ack.\n- if !seg.parsedOptions.TS && s.rttMeasureSeqNum.LessThan(seg.ackNumber) {\n+ if !rcvdSeg.parsedOptions.TS && s.rttMeasureSeqNum.LessThan(rcvdSeg.ackNumber) {\ns.updateRTO(time.Now().Sub(s.rttMeasureTime))\ns.rttMeasureSeqNum = s.sndNxt\n}\n// Update Timestamp if required. See RFC7323, section-4.3.\n- if s.ep.sendTSOk && seg.parsedOptions.TS {\n- s.ep.updateRecentTimestamp(seg.parsedOptions.TSVal, s.maxSentAck, seg.sequenceNumber)\n+ if s.ep.sendTSOk && rcvdSeg.parsedOptions.TS {\n+ s.ep.updateRecentTimestamp(rcvdSeg.parsedOptions.TSVal, s.maxSentAck, rcvdSeg.sequenceNumber)\n}\n// Insert SACKBlock information into our scoreboard.\nif s.ep.sackPermitted {\n- for _, sb := range seg.parsedOptions.SACKBlocks {\n+ for _, sb := range rcvdSeg.parsedOptions.SACKBlocks {\n// Only insert the SACK block if the following holds\n// true:\n// * SACK block acks data after the ack number in the\n@@ -1299,27 +1303,27 @@ func (s *sender) handleRcvdSegment(seg *segment) {\n// NOTE: This check specifically excludes DSACK blocks\n// which have start/end before sndUna and are used to\n// indicate spurious retransmissions.\n- if seg.ackNumber.LessThan(sb.Start) && s.sndUna.LessThan(sb.Start) && sb.End.LessThanEq(s.sndNxt) && !s.ep.scoreboard.IsSACKED(sb) {\n+ if rcvdSeg.ackNumber.LessThan(sb.Start) && s.sndUna.LessThan(sb.Start) && sb.End.LessThanEq(s.sndNxt) && !s.ep.scoreboard.IsSACKED(sb) {\ns.ep.scoreboard.Insert(sb)\n- seg.hasNewSACKInfo = true\n+ rcvdSeg.hasNewSACKInfo = true\n}\n}\ns.SetPipe()\n}\n// Count the duplicates and do the fast retransmit if needed.\n- rtx := s.checkDuplicateAck(seg)\n+ rtx := s.checkDuplicateAck(rcvdSeg)\n// Stash away the current window size.\n- s.sndWnd = seg.window\n+ s.sndWnd = rcvdSeg.window\n- ack := seg.ackNumber\n+ ack := rcvdSeg.ackNumber\n// Disable zero window probing if remote advertizes a non-zero receive\n// window. This can be with an ACK to the zero window probe (where the\n// acknumber refers to the already acknowledged byte) OR to any previously\n// unacknowledged segment.\n- if s.zeroWindowProbing && seg.window > 0 &&\n+ if s.zeroWindowProbing && rcvdSeg.window > 0 &&\n(ack == s.sndUna || (ack-1).InRange(s.sndUna, s.sndNxt)) {\ns.disableZeroWindowProbing()\n}\n@@ -1344,10 +1348,10 @@ func (s *sender) handleRcvdSegment(seg *segment) {\n// averaged RTT measurement only if the segment acknowledges\n// some new data, i.e., only if it advances the left edge of\n// the send window.\n- if s.ep.sendTSOk && seg.parsedOptions.TSEcr != 0 {\n+ if s.ep.sendTSOk && rcvdSeg.parsedOptions.TSEcr != 0 {\n// TSVal/Ecr values sent by Netstack are at a millisecond\n// granularity.\n- elapsed := time.Duration(s.ep.timestamp()-seg.parsedOptions.TSEcr) * time.Millisecond\n+ elapsed := time.Duration(s.ep.timestamp()-rcvdSeg.parsedOptions.TSEcr) * time.Millisecond\ns.updateRTO(elapsed)\n}\n@@ -1361,6 +1365,9 @@ func (s *sender) handleRcvdSegment(seg *segment) {\nackLeft := acked\noriginalOutstanding := s.outstanding\n+ s.rtt.Lock()\n+ srtt := s.rtt.srtt\n+ s.rtt.Unlock()\nfor ackLeft > 0 {\n// We use logicalLen here because we can have FIN\n// segments (which are always at the end of list) that\n@@ -1380,6 +1387,11 @@ func (s *sender) handleRcvdSegment(seg *segment) {\ns.writeNext = seg.Next()\n}\n+ // Update the RACK fields if SACK is enabled.\n+ if s.ep.sackPermitted {\n+ s.rc.Update(seg, rcvdSeg, srtt, s.ep.tsOffset)\n+ }\n+\ns.writeList.Remove(seg)\n// if SACK is enabled then Only reduce outstanding if\n@@ -1435,7 +1447,7 @@ func (s *sender) handleRcvdSegment(seg *segment) {\n// that the window opened up, or the congestion window was inflated due\n// to a duplicate ack during fast recovery. This will also re-enable\n// the retransmit timer if needed.\n- if !s.ep.sackPermitted || s.fr.active || s.dupAckCount == 0 || seg.hasNewSACKInfo {\n+ if !s.ep.sackPermitted || s.fr.active || s.dupAckCount == 0 || rcvdSeg.hasNewSACKInfo {\ns.sendData()\n}\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/transport/tcp/tcp_rack_test.go",
"diff": "+// Copyright 2020 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 tcp_test\n+\n+import (\n+ \"testing\"\n+ \"time\"\n+\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/transport/tcp/testing/context\"\n+)\n+\n+// TestRACKUpdate tests the RACK related fields are updated when an ACK is\n+// received on a SACK enabled connection.\n+func TestRACKUpdate(t *testing.T) {\n+ const maxPayload = 10\n+ const tsOptionSize = 12\n+ const maxTCPOptionSize = 40\n+\n+ c := context.New(t, uint32(header.TCPMinimumSize+header.IPv4MinimumSize+maxTCPOptionSize+maxPayload))\n+ defer c.Cleanup()\n+\n+ var xmitTime time.Time\n+ c.Stack().AddTCPProbe(func(state stack.TCPEndpointState) {\n+ // Validate that the endpoint Sender.RACKState is what we expect.\n+ if state.Sender.RACKState.XmitTime.Before(xmitTime) {\n+ t.Fatalf(\"RACK transmit time failed to update when an ACK is received\")\n+ }\n+\n+ gotSeq := state.Sender.RACKState.EndSequence\n+ wantSeq := state.Sender.SndNxt\n+ if !gotSeq.LessThanEq(wantSeq) || gotSeq.LessThan(wantSeq) {\n+ t.Fatalf(\"RACK sequence number failed to update, got: %v, but want: %v\", gotSeq, wantSeq)\n+ }\n+\n+ if state.Sender.RACKState.RTT == 0 {\n+ t.Fatalf(\"RACK RTT failed to update when an ACK is received\")\n+ }\n+ })\n+ setStackSACKPermitted(t, c, true)\n+ createConnectedWithSACKAndTS(c)\n+\n+ data := buffer.NewView(maxPayload)\n+ for i := range data {\n+ data[i] = byte(i)\n+ }\n+\n+ // Write the data.\n+ xmitTime = time.Now()\n+ if _, _, err := c.EP.Write(tcpip.SlicePayload(data), tcpip.WriteOptions{}); err != nil {\n+ t.Fatalf(\"Write failed: %s\", err)\n+ }\n+\n+ bytesRead := 0\n+ c.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\n+ bytesRead += maxPayload\n+ c.SendAck(790, bytesRead)\n+ time.Sleep(200 * time.Millisecond)\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update variables for implementation of RACK in TCP
RACK (Recent Acknowledgement) is a new loss detection
algorithm in TCP. These are the fields which should be
stored on connections to implement RACK algorithm.
PiperOrigin-RevId: 324948703 |
259,857 | 24.03.2020 12:40:52 | 0 | 6ce10c3c2ff516aabdef8b4d198690e7e7a87ca4 | amd64: introduce kernelEntry
kernelEntry is split from CPU that contains minimal CPU-specific
arch state that can be mapped at the upper of the address space.
It is prepared for KPTI for gvisor. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine_amd64.go",
"new_path": "pkg/sentry/platform/kvm/machine_amd64.go",
"diff": "@@ -144,6 +144,7 @@ func (c *vCPU) initArchState() error {\n// Set the entrypoint for the kernel.\nkernelUserRegs.RIP = uint64(reflect.ValueOf(ring0.Start).Pointer())\nkernelUserRegs.RAX = uint64(reflect.ValueOf(&c.CPU).Pointer())\n+ kernelUserRegs.RSP = c.StackTop()\nkernelUserRegs.RFLAGS = ring0.KernelFlagsSet\n// Set the system registers.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/defs_amd64.go",
"new_path": "pkg/sentry/platform/ring0/defs_amd64.go",
"diff": "@@ -80,14 +80,35 @@ type KernelArchState struct {\nglobalIDT idt64\n}\n-// CPUArchState contains CPU-specific arch state.\n-type CPUArchState struct {\n+// kernelEntry contains minimal CPU-specific arch state\n+// that can be mapped at the upper of the address space.\n+// Malicious APP might steal info from it via CPU bugs.\n+type kernelEntry struct {\n// stack is the stack used for interrupts on this CPU.\nstack [256]byte\n+ // scratch space for temporary usage.\n+ scratch0 uint64\n+ scratch1 uint64\n+\n+ // stackTop is the top of the stack.\n+ stackTop uint64\n+\n+ // cpuSelf is back reference to CPU.\n+ cpuSelf *CPU\n+\n// kernelCR3 is the cr3 used for sentry kernel.\nkernelCR3 uintptr\n+ // gdt is the CPU's descriptor table.\n+ gdt descriptorTable\n+\n+ // tss is the CPU's task state.\n+ tss TaskState64\n+}\n+\n+// CPUArchState contains CPU-specific arch state.\n+type CPUArchState struct {\n// errorCode is the error code from the last exception.\nerrorCode uintptr\n@@ -100,11 +121,7 @@ type CPUArchState struct {\n// exception.\nerrorType uintptr\n- // gdt is the CPU's descriptor table.\n- gdt descriptorTable\n-\n- // tss is the CPU's task state.\n- tss TaskState64\n+ *kernelEntry\n}\n// ErrorCode returns the last error code.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/kernel_amd64.go",
"new_path": "pkg/sentry/platform/ring0/kernel_amd64.go",
"diff": "@@ -41,6 +41,8 @@ func (k *Kernel) init(opts KernelOpts) {\n// init initializes architecture-specific state.\nfunc (c *CPU) init() {\n+ c.kernelEntry = &kernelEntry{}\n+ c.cpuSelf = c\n// Null segment.\nc.gdt[0].setNull()\n@@ -65,6 +67,7 @@ func (c *CPU) init() {\n// Set the kernel stack pointer in the TSS (virtual address).\nstackAddr := c.StackTop()\n+ c.stackTop = stackAddr\nc.tss.rsp0Lo = uint32(stackAddr)\nc.tss.rsp0Hi = uint32(stackAddr >> 32)\nc.tss.ist1Lo = uint32(stackAddr)\n@@ -215,7 +218,7 @@ func (c *CPU) SwitchToUser(switchOpts SwitchOpts) (vector Vector) {\n//go:nosplit\nfunc start(c *CPU) {\n// Save per-cpu & FS segment.\n- WriteGS(kernelAddr(c))\n+ WriteGS(kernelAddr(c.kernelEntry))\nWriteFS(uintptr(c.registers.Fs_base))\n// Initialize floating point.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/offsets_amd64.go",
"new_path": "pkg/sentry/platform/ring0/offsets_amd64.go",
"diff": "@@ -30,12 +30,18 @@ func Emit(w io.Writer) {\nc := &CPU{}\nfmt.Fprintf(w, \"\\n// CPU offsets.\\n\")\n- fmt.Fprintf(w, \"#define CPU_SELF 0x%02x\\n\", reflect.ValueOf(&c.self).Pointer()-reflect.ValueOf(c).Pointer())\nfmt.Fprintf(w, \"#define CPU_REGISTERS 0x%02x\\n\", reflect.ValueOf(&c.registers).Pointer()-reflect.ValueOf(c).Pointer())\n- fmt.Fprintf(w, \"#define CPU_STACK_TOP 0x%02x\\n\", reflect.ValueOf(&c.stack[0]).Pointer()-reflect.ValueOf(c).Pointer()+uintptr(len(c.stack)))\n- fmt.Fprintf(w, \"#define CPU_KERNEL_CR3 0x%02x\\n\", reflect.ValueOf(&c.kernelCR3).Pointer()-reflect.ValueOf(c).Pointer())\nfmt.Fprintf(w, \"#define CPU_ERROR_CODE 0x%02x\\n\", reflect.ValueOf(&c.errorCode).Pointer()-reflect.ValueOf(c).Pointer())\nfmt.Fprintf(w, \"#define CPU_ERROR_TYPE 0x%02x\\n\", reflect.ValueOf(&c.errorType).Pointer()-reflect.ValueOf(c).Pointer())\n+ fmt.Fprintf(w, \"#define CPU_ENTRY 0x%02x\\n\", reflect.ValueOf(&c.kernelEntry).Pointer()-reflect.ValueOf(c).Pointer())\n+\n+ e := &kernelEntry{}\n+ fmt.Fprintf(w, \"\\n// CPU entry offsets.\\n\")\n+ fmt.Fprintf(w, \"#define ENTRY_SCRATCH0 0x%02x\\n\", reflect.ValueOf(&e.scratch0).Pointer()-reflect.ValueOf(e).Pointer())\n+ fmt.Fprintf(w, \"#define ENTRY_SCRATCH1 0x%02x\\n\", reflect.ValueOf(&e.scratch1).Pointer()-reflect.ValueOf(e).Pointer())\n+ fmt.Fprintf(w, \"#define ENTRY_STACK_TOP 0x%02x\\n\", reflect.ValueOf(&e.stackTop).Pointer()-reflect.ValueOf(e).Pointer())\n+ fmt.Fprintf(w, \"#define ENTRY_CPU_SELF 0x%02x\\n\", reflect.ValueOf(&e.cpuSelf).Pointer()-reflect.ValueOf(e).Pointer())\n+ fmt.Fprintf(w, \"#define ENTRY_KERNEL_CR3 0x%02x\\n\", reflect.ValueOf(&e.kernelCR3).Pointer()-reflect.ValueOf(e).Pointer())\nfmt.Fprintf(w, \"\\n// Bits.\\n\")\nfmt.Fprintf(w, \"#define _RFLAGS_IF 0x%02x\\n\", _RFLAGS_IF)\n"
}
] | Go | Apache License 2.0 | google/gvisor | amd64: introduce kernelEntry
kernelEntry is split from CPU that contains minimal CPU-specific
arch state that can be mapped at the upper of the address space.
It is prepared for KPTI for gvisor.
Signed-off-by: Lai Jiangshan <[email protected]>
Signed-off-by: Lai Jiangshan <[email protected]> |
259,860 | 05.08.2020 08:33:52 | 25,200 | a2e129b540e530c56cb7648ae7e04325c6e763b1 | Add missing case in tmpfs.inode.direntType.
This was discovered by syzkaller. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"diff": "@@ -558,6 +558,8 @@ func (i *inode) direntType() uint8 {\nreturn linux.DT_LNK\ncase *socketFile:\nreturn linux.DT_SOCK\n+ case *namedPipe:\n+ return linux.DT_FIFO\ncase *deviceFile:\nswitch impl.kind {\ncase vfs.BlockDevice:\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add missing case in tmpfs.inode.direntType.
This was discovered by syzkaller.
PiperOrigin-RevId: 325025193 |
259,907 | 05.08.2020 10:21:17 | 25,200 | d0127b23f26d546db0d525201f0ad3f43d5b8d24 | [runtime tests] Update bugs and un-exclude passing tests. | [
{
"change_type": "MODIFY",
"old_path": "test/runtimes/exclude_nodejs12.4.0.csv",
"new_path": "test/runtimes/exclude_nodejs12.4.0.csv",
"diff": "@@ -11,6 +11,7 @@ parallel/test-dgram-socket-buffer-size.js,b/68847921,\nparallel/test-dns-channel-timeout.js,b/161893056,\nparallel/test-fs-access.js,,\nparallel/test-fs-watchfile.js,,Flaky - File already exists error\n+parallel/test-fs-write-stream.js,,Flaky\nparallel/test-fs-write-stream-throw-type-error.js,b/110226209,\nparallel/test-http-writable-true-after-close.js,,Flaky - Mismatched <anonymous> function calls. Expected exactly 1 actual 2\nparallel/test-os.js,b/63997097,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runtimes/exclude_php7.3.6.csv",
"new_path": "test/runtimes/exclude_php7.3.6.csv",
"diff": "@@ -12,20 +12,18 @@ ext/session/tests/session_module_name_variation4.phpt,,Flaky\next/session/tests/session_set_save_handler_class_018.phpt,,\next/session/tests/session_set_save_handler_iface_003.phpt,,\next/session/tests/session_set_save_handler_variation4.phpt,,\n-ext/session/tests/session_set_save_handler_variation5.phpt,,\n-ext/standard/tests/file/filetype_variation.phpt,,\n-ext/standard/tests/file/fopen_variation19.phpt,,\n+ext/standard/tests/file/fopen_variation19.phpt,b/162894964,\n+ext/standard/tests/file/lstat_stat_variation14.phpt,,Flaky\next/standard/tests/file/php_fd_wrapper_01.phpt,,\next/standard/tests/file/php_fd_wrapper_02.phpt,,\next/standard/tests/file/php_fd_wrapper_03.phpt,,\next/standard/tests/file/php_fd_wrapper_04.phpt,,\n-ext/standard/tests/file/realpath_bug77484.phpt,,\n+ext/standard/tests/file/realpath_bug77484.phpt,b/162894969,\next/standard/tests/file/rename_variation.phpt,b/68717309,\n-ext/standard/tests/file/symlink_link_linkinfo_is_link_variation4.phpt,,\n-ext/standard/tests/file/symlink_link_linkinfo_is_link_variation8.phpt,,\n+ext/standard/tests/file/symlink_link_linkinfo_is_link_variation4.phpt,b/162895341,\n+ext/standard/tests/file/symlink_link_linkinfo_is_link_variation8.phpt,b/162896223,\next/standard/tests/general_functions/escapeshellarg_bug71270.phpt,,\next/standard/tests/general_functions/escapeshellcmd_bug71270.phpt,,\n-ext/standard/tests/network/bug20134.phpt,,\next/standard/tests/streams/proc_open_bug69900.phpt,,Flaky\next/standard/tests/streams/stream_socket_sendto.phpt,,\next/standard/tests/strings/007.phpt,,\n@@ -36,4 +34,4 @@ tests/output/stream_isatty_in-out-err.phpt,,\ntests/output/stream_isatty_in-out.phpt,b/68720299,\ntests/output/stream_isatty_out-err.phpt,b/68720311,\ntests/output/stream_isatty_out.phpt,b/68720325,\n-Zend/tests/concat_003.phpt,,\n+Zend/tests/concat_003.phpt,b/162896021,\n"
}
] | Go | Apache License 2.0 | google/gvisor | [runtime tests] Update bugs and un-exclude passing tests.
PiperOrigin-RevId: 325045486 |
259,992 | 05.08.2020 11:28:15 | 25,200 | 190b1e6bd4aae56eff3ff846efea38629361b3a9 | Stop profiling when the sentry exits
Also removes `--profile-goroutine` because it's equivalent
to `debug --stacks`. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/control/pprof.go",
"new_path": "pkg/sentry/control/pprof.go",
"diff": "@@ -49,6 +49,9 @@ type ProfileOpts struct {\n// - dump out the stack trace of current go routines.\n// sentryctl -pid <pid> pprof-goroutine\ntype Profile struct {\n+ // Kernel is the kernel under profile. It's immutable.\n+ Kernel *kernel.Kernel\n+\n// mu protects the fields below.\nmu sync.Mutex\n@@ -57,9 +60,6 @@ type Profile struct {\n// traceFile is the current execution trace output file.\ntraceFile *fd.FD\n-\n- // Kernel is the kernel under profile.\n- Kernel *kernel.Kernel\n}\n// StartCPUProfile is an RPC stub which starts recording the CPU profile in a\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/test/dockerutil/profile.go",
"new_path": "pkg/test/dockerutil/profile.go",
"diff": "@@ -52,7 +52,6 @@ type Pprof struct {\nBasePath string // path to put profiles\nBlockProfile bool\nCPUProfile bool\n- GoRoutineProfile bool\nHeapProfile bool\nMutexProfile bool\nDuration time.Duration // duration to run profiler e.g. '10s' or '1m'.\n@@ -71,7 +70,6 @@ func MakePprofFromFlags(c *Container) *Pprof {\nBasePath: filepath.Join(*pprofBaseDir, c.runtime, c.Name),\nBlockProfile: *pprofBlock,\nCPUProfile: *pprofCPU,\n- GoRoutineProfile: *pprofGo,\nHeapProfile: *pprofHeap,\nMutexProfile: *pprofMutex,\nDuration: *duration,\n@@ -138,9 +136,6 @@ func (p *Pprof) makeProfileArgs(c *Container) []string {\nif p.CPUProfile {\nret = append(ret, fmt.Sprintf(\"--profile-cpu=%s\", filepath.Join(p.BasePath, \"cpu.pprof\")))\n}\n- if p.GoRoutineProfile {\n- ret = append(ret, fmt.Sprintf(\"--profile-goroutine=%s\", filepath.Join(p.BasePath, \"go.pprof\")))\n- }\nif p.HeapProfile {\nret = append(ret, fmt.Sprintf(\"--profile-heap=%s\", filepath.Join(p.BasePath, \"heap.pprof\")))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/test/dockerutil/profile_test.go",
"new_path": "pkg/test/dockerutil/profile_test.go",
"diff": "@@ -54,7 +54,6 @@ func TestPprof(t *testing.T) {\nBasePath: basePath,\nBlockProfile: true,\nCPUProfile: true,\n- GoRoutineProfile: true,\nHeapProfile: true,\nMutexProfile: true,\nDuration: 2 * time.Second,\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/controller.go",
"new_path": "runsc/boot/controller.go",
"diff": "@@ -104,7 +104,6 @@ const (\nStartCPUProfile = \"Profile.StartCPUProfile\"\nStopCPUProfile = \"Profile.StopCPUProfile\"\nHeapProfile = \"Profile.HeapProfile\"\n- GoroutineProfile = \"Profile.GoroutineProfile\"\nBlockProfile = \"Profile.BlockProfile\"\nMutexProfile = \"Profile.MutexProfile\"\nStartTrace = \"Profile.StartTrace\"\n@@ -129,42 +128,52 @@ type controller struct {\n// manager holds the containerManager methods.\nmanager *containerManager\n+\n+ // pprop holds the profile instance if enabled. It may be nil.\n+ pprof *control.Profile\n}\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- srv, err := server.CreateFromFD(fd)\n+ ctrl := &controller{}\n+ var err error\n+ ctrl.srv, err = server.CreateFromFD(fd)\nif err != nil {\nreturn nil, err\n}\n- manager := &containerManager{\n+ ctrl.manager = &containerManager{\nstartChan: make(chan struct{}),\nstartResultChan: make(chan error),\nl: l,\n}\n- srv.Register(manager)\n+ ctrl.srv.Register(ctrl.manager)\nif eps, ok := l.k.RootNetworkNamespace().Stack().(*netstack.Stack); ok {\nnet := &Network{\nStack: eps.Stack,\n}\n- srv.Register(net)\n+ ctrl.srv.Register(net)\n}\n- srv.Register(&debug{})\n- srv.Register(&control.Logging{})\n+ ctrl.srv.Register(&debug{})\n+ ctrl.srv.Register(&control.Logging{})\n+\nif l.root.conf.ProfileEnable {\n- srv.Register(&control.Profile{\n- Kernel: l.k,\n- })\n+ ctrl.pprof = &control.Profile{Kernel: l.k}\n+ ctrl.srv.Register(ctrl.pprof)\n}\n- return &controller{\n- srv: srv,\n- manager: manager,\n- }, nil\n+ return ctrl, nil\n+}\n+\n+func (c *controller) stop() {\n+ if c.pprof != nil {\n+ // These are noop if there is nothing being profiled.\n+ _ = c.pprof.StopCPUProfile(nil, nil)\n+ _ = c.pprof.StopTrace(nil, nil)\n+ }\n}\n// containerManager manages sandbox containers.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -1008,6 +1008,9 @@ func (l *Loader) WaitExit() kernel.ExitStatus {\n// Wait for container.\nl.k.WaitExited()\n+ // Cleanup\n+ l.ctrl.stop()\n+\nreturn l.k.GlobalInit().ExitStatus()\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/debug.go",
"new_path": "runsc/cmd/debug.go",
"diff": "@@ -37,7 +37,6 @@ type Debug struct {\nsignal int\nprofileHeap string\nprofileCPU string\n- profileGoroutine string\nprofileBlock string\nprofileMutex string\ntrace string\n@@ -69,7 +68,6 @@ func (d *Debug) SetFlags(f *flag.FlagSet) {\nf.BoolVar(&d.stacks, \"stacks\", false, \"if true, dumps all sandbox stacks to the log\")\nf.StringVar(&d.profileHeap, \"profile-heap\", \"\", \"writes heap profile to the given file.\")\nf.StringVar(&d.profileCPU, \"profile-cpu\", \"\", \"writes CPU profile to the given file.\")\n- f.StringVar(&d.profileGoroutine, \"profile-goroutine\", \"\", \"writes goroutine profile to the given file.\")\nf.StringVar(&d.profileBlock, \"profile-block\", \"\", \"writes block profile to the given file.\")\nf.StringVar(&d.profileMutex, \"profile-mutex\", \"\", \"writes mutex profile to the given file.\")\nf.DurationVar(&d.duration, \"duration\", time.Second, \"amount of time to wait for CPU and trace profiles\")\n@@ -153,18 +151,6 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n}\nlog.Infof(\"Heap profile written to %q\", d.profileHeap)\n}\n- if d.profileGoroutine != \"\" {\n- f, err := os.Create(d.profileGoroutine)\n- if err != nil {\n- return Errorf(err.Error())\n- }\n- defer f.Close()\n-\n- if err := c.Sandbox.GoroutineProfile(f); err != nil {\n- return Errorf(err.Error())\n- }\n- log.Infof(\"Goroutine profile written to %q\", d.profileGoroutine)\n- }\nif d.profileBlock != \"\" {\nf, err := os.Create(d.profileBlock)\nif err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -1012,26 +1012,6 @@ func (s *Sandbox) StopCPUProfile() error {\nreturn nil\n}\n-// GoroutineProfile writes a goroutine profile to the given file.\n-func (s *Sandbox) GoroutineProfile(f *os.File) error {\n- log.Debugf(\"Goroutine profile %q\", s.ID)\n- conn, err := s.sandboxConnect()\n- if err != nil {\n- return err\n- }\n- defer conn.Close()\n-\n- opts := control.ProfileOpts{\n- FilePayload: urpc.FilePayload{\n- Files: []*os.File{f},\n- },\n- }\n- if err := conn.Call(boot.GoroutineProfile, &opts, nil); err != nil {\n- return fmt.Errorf(\"getting sandbox %q goroutine profile: %v\", s.ID, err)\n- }\n- return nil\n-}\n-\n// BlockProfile writes a block profile to the given file.\nfunc (s *Sandbox) BlockProfile(f *os.File) error {\nlog.Debugf(\"Block profile %q\", s.ID)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Stop profiling when the sentry exits
Also removes `--profile-goroutine` because it's equivalent
to `debug --stacks`.
PiperOrigin-RevId: 325061502 |
259,962 | 05.08.2020 14:09:26 | 25,200 | e7b232a5b881c8930db968a7709ebd93cb2cab04 | Prefer RLock over Lock in functions that don't need Lock().
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -1985,8 +1985,8 @@ func generateRandInt64() int64 {\n// FindNetworkEndpoint returns the network endpoint for the given address.\nfunc (s *Stack) FindNetworkEndpoint(netProto tcpip.NetworkProtocolNumber, address tcpip.Address) (NetworkEndpoint, *tcpip.Error) {\n- s.mu.Lock()\n- defer s.mu.Unlock()\n+ s.mu.RLock()\n+ defer s.mu.RUnlock()\nfor _, nic := range s.nics {\nid := NetworkEndpointID{address}\n@@ -2005,8 +2005,8 @@ func (s *Stack) FindNetworkEndpoint(netProto tcpip.NetworkProtocolNumber, addres\n// FindNICNameFromID returns the name of the nic for the given NICID.\nfunc (s *Stack) FindNICNameFromID(id tcpip.NICID) string {\n- s.mu.Lock()\n- defer s.mu.Unlock()\n+ s.mu.RLock()\n+ defer s.mu.RUnlock()\nnic, ok := s.nics[id]\nif !ok {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Prefer RLock over Lock in functions that don't need Lock().
Updates #231
PiperOrigin-RevId: 325097683 |
259,860 | 05.08.2020 16:14:40 | 25,200 | 1403a88c67ccc87af383f5e54fd2f77c673eebe7 | Release extra memfd reference. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/memfd.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/memfd.go",
"diff": "@@ -51,6 +51,7 @@ func MemfdCreate(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.S\nif err != nil {\nreturn 0, nil, err\n}\n+ defer file.DecRef(t)\nfd, err := t.NewFDFromVFS2(0, file, kernel.FDFlags{\nCloseOnExec: cloExec,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Release extra memfd reference.
PiperOrigin-RevId: 325122849 |
260,004 | 05.08.2020 17:30:39 | 25,200 | 90a2d4e8238a9a92b77d363439485d3e8b2211ac | Support receiving broadcast IPv4 packets
Test: integration_test.TestIncomingSubnetBroadcast | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -609,6 +609,9 @@ func (n *NIC) findEndpoint(protocol tcpip.NetworkProtocolNumber, address tcpip.A\n// If none exists a temporary one may be created if we are in promiscuous mode\n// or spoofing. Promiscuous mode will only be checked if promiscuous is true.\n// Similarly, spoofing will only be checked if spoofing is true.\n+//\n+// If the address is the IPv4 broadcast address for an endpoint's network, that\n+// endpoint will be returned.\nfunc (n *NIC) getRefOrCreateTemp(protocol tcpip.NetworkProtocolNumber, address tcpip.Address, peb PrimaryEndpointBehavior, tempRef getRefBehaviour) *referencedNetworkEndpoint {\nn.mu.RLock()\n@@ -633,6 +636,16 @@ func (n *NIC) getRefOrCreateTemp(protocol tcpip.NetworkProtocolNumber, address t\n}\n}\n+ // Check if address is a broadcast address for the endpoint's network.\n+ //\n+ // Only IPv4 has a notion of broadcast addresses.\n+ if protocol == header.IPv4ProtocolNumber {\n+ if ref := n.getRefForBroadcastRLocked(address); ref != nil {\n+ n.mu.RUnlock()\n+ return ref\n+ }\n+ }\n+\n// A usable reference was not found, create a temporary one if requested by\n// the caller or if the address is found in the NIC's subnets.\ncreateTempEP := spoofingOrPromiscuous\n@@ -670,8 +683,34 @@ func (n *NIC) getRefOrCreateTemp(protocol tcpip.NetworkProtocolNumber, address t\nreturn ref\n}\n+// getRefForBroadcastLocked returns an endpoint where address is the IPv4\n+// broadcast address for the endpoint's network.\n+//\n+// n.mu MUST be read locked.\n+func (n *NIC) getRefForBroadcastRLocked(address tcpip.Address) *referencedNetworkEndpoint {\n+ for _, ref := range n.mu.endpoints {\n+ // Only IPv4 has a notion of broadcast addresses.\n+ if ref.protocol != header.IPv4ProtocolNumber {\n+ continue\n+ }\n+\n+ addr := ref.addrWithPrefix()\n+ subnet := addr.Subnet()\n+ if subnet.IsBroadcast(address) && ref.tryIncRef() {\n+ return ref\n+ }\n+ }\n+\n+ return nil\n+}\n+\n/// getRefOrCreateTempLocked returns an existing endpoint for address or creates\n/// and returns a temporary endpoint.\n+//\n+// If the address is the IPv4 broadcast address for an endpoint's network, that\n+// endpoint will be returned.\n+//\n+// n.mu must be write locked.\nfunc (n *NIC) getRefOrCreateTempLocked(protocol tcpip.NetworkProtocolNumber, address tcpip.Address, peb PrimaryEndpointBehavior) *referencedNetworkEndpoint {\nif ref, ok := n.mu.endpoints[NetworkEndpointID{address}]; ok {\n// No need to check the type as we are ok with expired endpoints at this\n@@ -685,6 +724,15 @@ func (n *NIC) getRefOrCreateTempLocked(protocol tcpip.NetworkProtocolNumber, add\nn.removeEndpointLocked(ref)\n}\n+ // Check if address is a broadcast address for an endpoint's network.\n+ //\n+ // Only IPv4 has a notion of broadcast addresses.\n+ if protocol == header.IPv4ProtocolNumber {\n+ if ref := n.getRefForBroadcastRLocked(address); ref != nil {\n+ return ref\n+ }\n+ }\n+\n// Add a new temporary endpoint.\nnetProto, ok := n.stack.networkProtocols[protocol]\nif !ok {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -1704,7 +1704,7 @@ func testNicForAddressRange(t *testing.T, nicID tcpip.NICID, s *stack.Stack, sub\n// Trying the next address should always fail since it is outside the range.\nif gotNicID := s.CheckLocalAddress(0, fakeNetNumber, tcpip.Address(addrBytes)); gotNicID != 0 {\n- t.Errorf(\"got CheckLocalAddress(0, %d, %s) = %d, want = %d\", fakeNetNumber, tcpip.Address(addrBytes), gotNicID, 0)\n+ t.Errorf(\"got CheckLocalAddress(0, %d, %s) = %d, want = 0\", fakeNetNumber, tcpip.Address(addrBytes), gotNicID)\n}\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/tests/integration/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_test\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_test(\n+ name = \"integration_test\",\n+ size = \"small\",\n+ srcs = [\"multicast_broadcast_test.go\"],\n+ deps = [\n+ \"//pkg/tcpip\",\n+ \"//pkg/tcpip/buffer\",\n+ \"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/link/channel\",\n+ \"//pkg/tcpip/network/ipv4\",\n+ \"//pkg/tcpip/network/ipv6\",\n+ \"//pkg/tcpip/stack\",\n+ \"//pkg/tcpip/transport/udp\",\n+ \"//pkg/waiter\",\n+ \"@com_github_google_go_cmp//cmp:go_default_library\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/tests/integration/multicast_broadcast_test.go",
"diff": "+// Copyright 2020 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 integration_test\n+\n+import (\n+ \"testing\"\n+\n+ \"github.com/google/go-cmp/cmp\"\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/link/channel\"\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/udp\"\n+ \"gvisor.dev/gvisor/pkg/waiter\"\n+)\n+\n+const defaultMTU = 1280\n+\n+func TestIncomingSubnetBroadcast(t *testing.T) {\n+ const (\n+ nicID = 1\n+ remotePort = 5555\n+ localPort = 80\n+ ttl = 255\n+ )\n+\n+ data := []byte{1, 2, 3, 4}\n+\n+ // Local IPv4 subnet: 192.168.1.58/24\n+ ipv4Addr := tcpip.AddressWithPrefix{\n+ Address: \"\\xc0\\xa8\\x01\\x3a\",\n+ PrefixLen: 24,\n+ }\n+ ipv4Subnet := ipv4Addr.Subnet()\n+ ipv4SubnetBcast := ipv4Subnet.Broadcast()\n+\n+ // Local IPv6 subnet: 200a::1/64\n+ ipv6Addr := tcpip.AddressWithPrefix{\n+ Address: \"\\x20\\x0a\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\",\n+ PrefixLen: 64,\n+ }\n+ ipv6Subnet := ipv6Addr.Subnet()\n+ ipv6SubnetBcast := ipv6Subnet.Broadcast()\n+\n+ // Remote addrs.\n+ remoteIPv4Addr := tcpip.Address(\"\\x64\\x0a\\x7b\\x18\")\n+ remoteIPv6Addr := tcpip.Address(\"\\x20\\x0b\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\")\n+\n+ rxIPv4UDP := func(e *channel.Endpoint, dst tcpip.Address) {\n+ payloadLen := header.UDPMinimumSize + len(data)\n+ totalLen := header.IPv4MinimumSize + payloadLen\n+ hdr := buffer.NewPrependable(totalLen)\n+ u := header.UDP(hdr.Prepend(payloadLen))\n+ u.Encode(&header.UDPFields{\n+ SrcPort: remotePort,\n+ DstPort: localPort,\n+ Length: uint16(payloadLen),\n+ })\n+ copy(u.Payload(), data)\n+ sum := header.PseudoHeaderChecksum(udp.ProtocolNumber, remoteIPv4Addr, dst, uint16(payloadLen))\n+ sum = header.Checksum(data, sum)\n+ u.SetChecksum(^u.CalculateChecksum(sum))\n+\n+ ip := header.IPv4(hdr.Prepend(header.IPv4MinimumSize))\n+ ip.Encode(&header.IPv4Fields{\n+ IHL: header.IPv4MinimumSize,\n+ TotalLength: uint16(totalLen),\n+ Protocol: uint8(udp.ProtocolNumber),\n+ TTL: ttl,\n+ SrcAddr: remoteIPv4Addr,\n+ DstAddr: dst,\n+ })\n+\n+ e.InjectInbound(header.IPv4ProtocolNumber, &stack.PacketBuffer{\n+ Data: hdr.View().ToVectorisedView(),\n+ })\n+ }\n+\n+ rxIPv6UDP := func(e *channel.Endpoint, dst tcpip.Address) {\n+ payloadLen := header.UDPMinimumSize + len(data)\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + payloadLen)\n+ u := header.UDP(hdr.Prepend(payloadLen))\n+ u.Encode(&header.UDPFields{\n+ SrcPort: remotePort,\n+ DstPort: localPort,\n+ Length: uint16(payloadLen),\n+ })\n+ copy(u.Payload(), data)\n+ sum := header.PseudoHeaderChecksum(udp.ProtocolNumber, remoteIPv6Addr, dst, uint16(payloadLen))\n+ sum = header.Checksum(data, sum)\n+ u.SetChecksum(^u.CalculateChecksum(sum))\n+\n+ ip := header.IPv6(hdr.Prepend(header.IPv6MinimumSize))\n+ ip.Encode(&header.IPv6Fields{\n+ PayloadLength: uint16(payloadLen),\n+ NextHeader: uint8(udp.ProtocolNumber),\n+ HopLimit: ttl,\n+ SrcAddr: remoteIPv6Addr,\n+ DstAddr: dst,\n+ })\n+\n+ e.InjectInbound(header.IPv6ProtocolNumber, &stack.PacketBuffer{\n+ Data: hdr.View().ToVectorisedView(),\n+ })\n+ }\n+\n+ tests := []struct {\n+ name string\n+ bindAddr tcpip.Address\n+ dstAddr tcpip.Address\n+ expectRx bool\n+ }{\n+ {\n+ name: \"IPv4 unicast binding to unicast\",\n+ bindAddr: ipv4Addr.Address,\n+ dstAddr: ipv4Addr.Address,\n+ expectRx: true,\n+ },\n+ {\n+ name: \"IPv4 unicast binding to broadcast\",\n+ bindAddr: header.IPv4Broadcast,\n+ dstAddr: ipv4Addr.Address,\n+ expectRx: false,\n+ },\n+ {\n+ name: \"IPv4 unicast binding to wildcard\",\n+ dstAddr: ipv4Addr.Address,\n+ expectRx: true,\n+ },\n+\n+ {\n+ name: \"IPv4 directed broadcast binding to subnet broadcast\",\n+ bindAddr: ipv4SubnetBcast,\n+ dstAddr: ipv4SubnetBcast,\n+ expectRx: true,\n+ },\n+ {\n+ name: \"IPv4 directed broadcast binding to broadcast\",\n+ bindAddr: header.IPv4Broadcast,\n+ dstAddr: ipv4SubnetBcast,\n+ expectRx: false,\n+ },\n+ {\n+ name: \"IPv4 directed broadcast binding to wildcard\",\n+ dstAddr: ipv4SubnetBcast,\n+ expectRx: true,\n+ },\n+\n+ {\n+ name: \"IPv4 broadcast binding to broadcast\",\n+ bindAddr: header.IPv4Broadcast,\n+ dstAddr: header.IPv4Broadcast,\n+ expectRx: true,\n+ },\n+ {\n+ name: \"IPv4 broadcast binding to subnet broadcast\",\n+ bindAddr: ipv4SubnetBcast,\n+ dstAddr: header.IPv4Broadcast,\n+ expectRx: false,\n+ },\n+ {\n+ name: \"IPv4 broadcast binding to wildcard\",\n+ dstAddr: ipv4SubnetBcast,\n+ expectRx: true,\n+ },\n+\n+ // IPv6 has no notion of a broadcast.\n+ {\n+ name: \"IPv6 unicast binding to wildcard\",\n+ dstAddr: ipv6Addr.Address,\n+ expectRx: true,\n+ },\n+ {\n+ name: \"IPv6 broadcast-like address binding to wildcard\",\n+ dstAddr: ipv6SubnetBcast,\n+ expectRx: false,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{ipv4.NewProtocol(), ipv6.NewProtocol()},\n+ TransportProtocols: []stack.TransportProtocol{udp.NewProtocol()},\n+ })\n+ e := channel.New(0, defaultMTU, \"\")\n+ if err := s.CreateNIC(nicID, e); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID, err)\n+ }\n+ ipv4ProtoAddr := tcpip.ProtocolAddress{Protocol: header.IPv4ProtocolNumber, AddressWithPrefix: ipv4Addr}\n+ if err := s.AddProtocolAddress(nicID, ipv4ProtoAddr); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %+v): %s\", nicID, ipv4ProtoAddr, err)\n+ }\n+ ipv6ProtoAddr := tcpip.ProtocolAddress{Protocol: header.IPv6ProtocolNumber, AddressWithPrefix: ipv6Addr}\n+ if err := s.AddProtocolAddress(nicID, ipv6ProtoAddr); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %+v): %s\", nicID, ipv6ProtoAddr, err)\n+ }\n+\n+ var netproto tcpip.NetworkProtocolNumber\n+ var rxUDP func(*channel.Endpoint, tcpip.Address)\n+ switch l := len(test.dstAddr); l {\n+ case header.IPv4AddressSize:\n+ netproto = header.IPv4ProtocolNumber\n+ rxUDP = rxIPv4UDP\n+ case header.IPv6AddressSize:\n+ netproto = header.IPv6ProtocolNumber\n+ rxUDP = rxIPv6UDP\n+ default:\n+ t.Fatalf(\"got unexpected address length = %d bytes\", l)\n+ }\n+\n+ wq := waiter.Queue{}\n+ ep, err := s.NewEndpoint(udp.ProtocolNumber, netproto, &wq)\n+ if err != nil {\n+ t.Fatalf(\"NewEndpoint(%d, %d, _): %s\", udp.ProtocolNumber, netproto, err)\n+ }\n+ defer ep.Close()\n+\n+ bindAddr := tcpip.FullAddress{Addr: test.bindAddr, Port: localPort}\n+ if err := ep.Bind(bindAddr); err != nil {\n+ t.Fatalf(\"ep.Bind(%+v): %s\", bindAddr, err)\n+ }\n+\n+ rxUDP(e, test.dstAddr)\n+ if gotPayload, _, err := ep.Read(nil); test.expectRx {\n+ if err != nil {\n+ t.Fatalf(\"Read(nil): %s\", err)\n+ }\n+ if diff := cmp.Diff(buffer.View(data), gotPayload); diff != \"\" {\n+ t.Errorf(\"got UDP payload mismatch (-want +got):\\n%s\", diff)\n+ }\n+ } else {\n+ if err != tcpip.ErrWouldBlock {\n+ t.Fatalf(\"got Read(nil) = (%x, _, %v), want = (_, _, %s)\", gotPayload, err, tcpip.ErrWouldBlock)\n+ }\n+ }\n+ })\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Support receiving broadcast IPv4 packets
Test: integration_test.TestIncomingSubnetBroadcast
PiperOrigin-RevId: 325135617 |
259,907 | 05.08.2020 17:46:13 | 25,200 | ce463c027b0d3cbcf3b9d3e2a5ad598c0249212f | [runtime tests] Update python tests.
un-exclude passing tests to increase testing surface.
create/update bugs for tests that fail on runsc but pass on runc. | [
{
"change_type": "MODIFY",
"old_path": "test/runtimes/exclude_python3.7.3.csv",
"new_path": "test/runtimes/exclude_python3.7.3.csv",
"diff": "test name,bug id,comment\n-test_asynchat,b/76031995,SO_REUSEADDR\ntest_asyncio,,Fails on Docker.\n-test_asyncore,b/76031995,SO_REUSEADDR\n-test_epoll,,\n-test_fcntl,,fcntl invalid argument -- artificial test to make sure something works in 64 bit mode.\n-test_ftplib,,Fails in Docker\n-test_httplib,b/76031995,SO_REUSEADDR\n-test_imaplib,,\n-test_logging,,\n+test_asyncore,b/162973328,\n+test_epoll,b/162983393,\n+test_fcntl,b/162978767,fcntl invalid argument -- artificial test to make sure something works in 64 bit mode.\n+test_imaplib,b/162979661,\n+test_logging,b/162980079,\ntest_multiprocessing_fork,,Flaky. Sometimes times out.\ntest_multiprocessing_forkserver,,Flaky. Sometimes times out.\ntest_multiprocessing_main_handling,,Flaky. Sometimes times out.\ntest_multiprocessing_spawn,,Flaky. Sometimes times out.\n-test_nntplib,b/76031995,tests should not set SO_REUSEADDR\n-test_poplib,,Fails on Docker\ntest_posix,b/76174079,posix.sched_get_priority_min not implemented + posix.sched_rr_get_interval not permitted\n-test_pty,b/76157709,out of pty devices\n-test_readline,b/76157709,out of pty devices\n+test_pty,b/162979921,\n+test_readline,b/162980389,TestReadline hangs forever\ntest_resource,b/76174079,\ntest_selectors,b/76116849,OSError not raised with epoll\n-test_smtplib,b/76031995,SO_REUSEADDR and unclosed sockets\n+test_smtplib,b/162980434,unclosed sockets\ntest_signal,,Flaky - signal: alarm clock\ntest_socket,b/75983380,\n-test_ssl,b/76031995,SO_REUSEADDR\n-test_subprocess,,\n-test_support,b/76031995,SO_REUSEADDR\n-test_telnetlib,b/76031995,SO_REUSEADDR\n+test_subprocess,b/162980831,\n"
}
] | Go | Apache License 2.0 | google/gvisor | [runtime tests] Update python tests.
- un-exclude passing tests to increase testing surface.
- create/update bugs for tests that fail on runsc but pass on runc.
PiperOrigin-RevId: 325137657 |
259,860 | 05.08.2020 18:15:01 | 25,200 | 7ed4b2b5a6928b3a4a88d0117a764dd4795be61a | Correctly decrement link counts in tmpfs rename operations.
When a directory is replaced by a rename operation, its link count should
reach zero. We were missing the link from `dir/.` | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"diff": "@@ -566,7 +566,9 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\nif replaced != nil {\nnewParentDir.removeChildLocked(replaced)\nif replaced.inode.isDir() {\n- newParentDir.inode.decLinksLocked(ctx) // from replaced's \"..\"\n+ // Remove links for replaced/. and replaced/..\n+ replaced.inode.decLinksLocked(ctx)\n+ newParentDir.inode.decLinksLocked(ctx)\n}\nreplaced.inode.decLinksLocked(ctx)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Correctly decrement link counts in tmpfs rename operations.
When a directory is replaced by a rename operation, its link count should
reach zero. We were missing the link from `dir/.`
PiperOrigin-RevId: 325141730 |
259,896 | 05.08.2020 20:45:02 | 25,200 | 35312a95c4c8626365b4ece5ffb0bcab44b4bede | Add loss recovery option for TCP.
/proc/sys/net/ipv4/tcp_recovery is used to enable RACK loss
recovery in TCP. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/sys_net.go",
"new_path": "pkg/sentry/fs/proc/sys_net.go",
"diff": "@@ -272,6 +272,96 @@ func (f *tcpSackFile) Write(ctx context.Context, _ *fs.File, src usermem.IOSeque\nreturn n, f.tcpSack.stack.SetTCPSACKEnabled(*f.tcpSack.enabled)\n}\n+// +stateify savable\n+type tcpRecovery struct {\n+ fsutil.SimpleFileInode\n+\n+ stack inet.Stack `state:\"wait\"`\n+ recovery inet.TCPLossRecovery\n+}\n+\n+func newTCPRecoveryInode(ctx context.Context, msrc *fs.MountSource, s inet.Stack) *fs.Inode {\n+ ts := &tcpRecovery{\n+ SimpleFileInode: *fsutil.NewSimpleFileInode(ctx, fs.RootOwner, fs.FilePermsFromMode(0644), linux.PROC_SUPER_MAGIC),\n+ stack: s,\n+ }\n+ sattr := fs.StableAttr{\n+ DeviceID: device.ProcDevice.DeviceID(),\n+ InodeID: device.ProcDevice.NextIno(),\n+ BlockSize: usermem.PageSize,\n+ Type: fs.SpecialFile,\n+ }\n+ return fs.NewInode(ctx, ts, msrc, sattr)\n+}\n+\n+// Truncate implements fs.InodeOperations.Truncate.\n+func (*tcpRecovery) Truncate(context.Context, *fs.Inode, int64) error {\n+ return nil\n+}\n+\n+// GetFile implements fs.InodeOperations.GetFile.\n+func (r *tcpRecovery) GetFile(ctx context.Context, dirent *fs.Dirent, flags fs.FileFlags) (*fs.File, error) {\n+ flags.Pread = true\n+ flags.Pwrite = true\n+ return fs.NewFile(ctx, dirent, flags, &tcpRecoveryFile{\n+ tcpRecovery: r,\n+ stack: r.stack,\n+ }), nil\n+}\n+\n+// +stateify savable\n+type tcpRecoveryFile struct {\n+ fsutil.FileGenericSeek `state:\"nosave\"`\n+ fsutil.FileNoIoctl `state:\"nosave\"`\n+ fsutil.FileNoMMap `state:\"nosave\"`\n+ fsutil.FileNoSplice `state:\"nosave\"`\n+ fsutil.FileNoopRelease `state:\"nosave\"`\n+ fsutil.FileNoopFlush `state:\"nosave\"`\n+ fsutil.FileNoopFsync `state:\"nosave\"`\n+ fsutil.FileNotDirReaddir `state:\"nosave\"`\n+ fsutil.FileUseInodeUnstableAttr `state:\"nosave\"`\n+ waiter.AlwaysReady `state:\"nosave\"`\n+\n+ tcpRecovery *tcpRecovery\n+\n+ stack inet.Stack `state:\"wait\"`\n+}\n+\n+// Read implements fs.FileOperations.Read.\n+func (f *tcpRecoveryFile) Read(ctx context.Context, _ *fs.File, dst usermem.IOSequence, offset int64) (int64, error) {\n+ if offset != 0 {\n+ return 0, io.EOF\n+ }\n+\n+ recovery, err := f.stack.TCPRecovery()\n+ if err != nil {\n+ return 0, err\n+ }\n+ f.tcpRecovery.recovery = recovery\n+ s := fmt.Sprintf(\"%d\\n\", f.tcpRecovery.recovery)\n+ n, err := dst.CopyOut(ctx, []byte(s))\n+ return int64(n), err\n+}\n+\n+// Write implements fs.FileOperations.Write.\n+func (f *tcpRecoveryFile) Write(ctx context.Context, _ *fs.File, src usermem.IOSequence, offset int64) (int64, error) {\n+ if src.NumBytes() == 0 {\n+ return 0, nil\n+ }\n+ src = src.TakeFirst(usermem.PageSize - 1)\n+\n+ var v int32\n+ n, err := usermem.CopyInt32StringInVec(ctx, src.IO, src.Addrs, &v, src.Opts)\n+ if err != nil {\n+ return 0, err\n+ }\n+ f.tcpRecovery.recovery = inet.TCPLossRecovery(v)\n+ if err := f.tcpRecovery.stack.SetTCPRecovery(f.tcpRecovery.recovery); err != nil {\n+ return 0, err\n+ }\n+ return n, nil\n+}\n+\nfunc (p *proc) newSysNetCore(ctx context.Context, msrc *fs.MountSource, s inet.Stack) *fs.Inode {\n// The following files are simple stubs until they are implemented in\n// netstack, most of these files are configuration related. We use the\n@@ -351,6 +441,11 @@ func (p *proc) newSysNetIPv4Dir(ctx context.Context, msrc *fs.MountSource, s ine\ncontents[\"tcp_wmem\"] = newTCPMemInode(ctx, msrc, s, tcpWMem)\n}\n+ // Add tcp_recovery.\n+ if _, err := s.TCPRecovery(); err == nil {\n+ contents[\"tcp_recovery\"] = newTCPRecoveryInode(ctx, msrc, s)\n+ }\n+\nd := ramfs.NewDir(ctx, contents, fs.RootOwner, fs.FilePermsFromMode(0555))\nreturn newProcInode(ctx, d, msrc, fs.SpecialDirectory, nil)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/tasks_sys.go",
"new_path": "pkg/sentry/fsimpl/proc/tasks_sys.go",
"diff": "@@ -55,6 +55,7 @@ func (fs *filesystem) newSysNetDir(root *auth.Credentials, k *kernel.Kernel) *ke\nif stack := k.RootNetworkNamespace().Stack(); stack != nil {\ncontents = map[string]*kernfs.Dentry{\n\"ipv4\": kernfs.NewStaticDir(root, linux.UNNAMED_MAJOR, fs.devMinor, fs.NextIno(), 0555, map[string]*kernfs.Dentry{\n+ \"tcp_recovery\": fs.newDentry(root, fs.NextIno(), 0644, &tcpRecoveryData{stack: stack}),\n\"tcp_sack\": fs.newDentry(root, fs.NextIno(), 0644, &tcpSackData{stack: stack}),\n// The following files are simple stubs until they are implemented in\n@@ -207,3 +208,49 @@ func (d *tcpSackData) Write(ctx context.Context, src usermem.IOSequence, offset\n*d.enabled = v != 0\nreturn n, d.stack.SetTCPSACKEnabled(*d.enabled)\n}\n+\n+// tcpRecoveryData implements vfs.WritableDynamicBytesSource for\n+// /proc/sys/net/ipv4/tcp_recovery.\n+//\n+// +stateify savable\n+type tcpRecoveryData struct {\n+ kernfs.DynamicBytesFile\n+\n+ stack inet.Stack `state:\"wait\"`\n+}\n+\n+var _ vfs.WritableDynamicBytesSource = (*tcpRecoveryData)(nil)\n+\n+// Generate implements vfs.DynamicBytesSource.\n+func (d *tcpRecoveryData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ recovery, err := d.stack.TCPRecovery()\n+ if err != nil {\n+ return err\n+ }\n+\n+ buf.WriteString(fmt.Sprintf(\"%d\\n\", recovery))\n+ return nil\n+}\n+\n+func (d *tcpRecoveryData) Write(ctx context.Context, src usermem.IOSequence, offset int64) (int64, error) {\n+ if offset != 0 {\n+ // No need to handle partial writes thus far.\n+ return 0, syserror.EINVAL\n+ }\n+ if src.NumBytes() == 0 {\n+ return 0, nil\n+ }\n+\n+ // Limit the amount of memory allocated.\n+ src = src.TakeFirst(usermem.PageSize - 1)\n+\n+ var v int32\n+ n, err := usermem.CopyInt32StringInVec(ctx, src.IO, src.Addrs, &v, src.Opts)\n+ if err != nil {\n+ return 0, err\n+ }\n+ if err := d.stack.SetTCPRecovery(inet.TCPLossRecovery(v)); err != nil {\n+ return 0, err\n+ }\n+ return n, nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/inet/inet.go",
"new_path": "pkg/sentry/inet/inet.go",
"diff": "@@ -56,6 +56,12 @@ type Stack interface {\n// settings.\nSetTCPSACKEnabled(enabled bool) error\n+ // TCPRecovery returns the TCP loss detection algorithm.\n+ TCPRecovery() (TCPLossRecovery, error)\n+\n+ // SetTCPRecovery attempts to change TCP loss detection algorithm.\n+ SetTCPRecovery(recovery TCPLossRecovery) error\n+\n// Statistics reports stack statistics.\nStatistics(stat interface{}, arg string) error\n@@ -189,3 +195,14 @@ type StatSNMPUDP [8]uint64\n// StatSNMPUDPLite describes UdpLite line of /proc/net/snmp.\ntype StatSNMPUDPLite [8]uint64\n+\n+// TCPLossRecovery indicates TCP loss detection and recovery methods to use.\n+type TCPLossRecovery int32\n+\n+// Loss recovery constants from include/net/tcp.h which are used to set\n+// /proc/sys/net/ipv4/tcp_recovery.\n+const (\n+ TCP_RACK_LOSS_DETECTION TCPLossRecovery = 1 << iota\n+ TCP_RACK_STATIC_REO_WND\n+ TCP_RACK_NO_DUPTHRESH\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/inet/test_stack.go",
"new_path": "pkg/sentry/inet/test_stack.go",
"diff": "@@ -25,6 +25,7 @@ type TestStack struct {\nTCPRecvBufSize TCPBufferSize\nTCPSendBufSize TCPBufferSize\nTCPSACKFlag bool\n+ Recovery TCPLossRecovery\n}\n// NewTestStack returns a TestStack with no network interfaces. The value of\n@@ -91,6 +92,17 @@ func (s *TestStack) SetTCPSACKEnabled(enabled bool) error {\nreturn nil\n}\n+// TCPRecovery implements Stack.TCPRecovery.\n+func (s *TestStack) TCPRecovery() (TCPLossRecovery, error) {\n+ return s.Recovery, nil\n+}\n+\n+// SetTCPRecovery implements Stack.SetTCPRecovery.\n+func (s *TestStack) SetTCPRecovery(recovery TCPLossRecovery) error {\n+ s.Recovery = recovery\n+ return nil\n+}\n+\n// Statistics implements inet.Stack.Statistics.\nfunc (s *TestStack) Statistics(stat interface{}, arg string) error {\nreturn nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/hostinet/stack.go",
"new_path": "pkg/sentry/socket/hostinet/stack.go",
"diff": "@@ -53,6 +53,7 @@ type Stack struct {\ninterfaceAddrs map[int32][]inet.InterfaceAddr\nroutes []inet.Route\nsupportsIPv6 bool\n+ tcpRecovery inet.TCPLossRecovery\ntcpRecvBufSize inet.TCPBufferSize\ntcpSendBufSize inet.TCPBufferSize\ntcpSACKEnabled bool\n@@ -350,6 +351,16 @@ func (s *Stack) SetTCPSACKEnabled(enabled bool) error {\nreturn syserror.EACCES\n}\n+// TCPRecovery implements inet.Stack.TCPRecovery.\n+func (s *Stack) TCPRecovery() (inet.TCPLossRecovery, error) {\n+ return s.tcpRecovery, nil\n+}\n+\n+// SetTCPRecovery implements inet.Stack.SetTCPRecovery.\n+func (s *Stack) SetTCPRecovery(recovery inet.TCPLossRecovery) error {\n+ return syserror.EACCES\n+}\n+\n// getLine reads one line from proc file, with specified prefix.\n// The last argument, withHeader, specifies if it contains line header.\nfunc getLine(f *os.File, prefix string, withHeader bool) string {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/stack.go",
"new_path": "pkg/sentry/socket/netstack/stack.go",
"diff": "@@ -207,6 +207,20 @@ func (s *Stack) SetTCPSACKEnabled(enabled bool) error {\nreturn syserr.TranslateNetstackError(s.Stack.SetTransportProtocolOption(tcp.ProtocolNumber, tcp.SACKEnabled(enabled))).ToError()\n}\n+// TCPRecovery implements inet.Stack.TCPRecovery.\n+func (s *Stack) TCPRecovery() (inet.TCPLossRecovery, error) {\n+ var recovery tcp.Recovery\n+ if err := s.Stack.TransportProtocolOption(tcp.ProtocolNumber, &recovery); err != nil {\n+ return 0, syserr.TranslateNetstackError(err).ToError()\n+ }\n+ return inet.TCPLossRecovery(recovery), nil\n+}\n+\n+// SetTCPRecovery implements inet.Stack.SetTCPRecovery.\n+func (s *Stack) SetTCPRecovery(recovery inet.TCPLossRecovery) error {\n+ return syserr.TranslateNetstackError(s.Stack.SetTransportProtocolOption(tcp.ProtocolNumber, tcp.Recovery(recovery))).ToError()\n+}\n+\n// Statistics implements inet.Stack.Statistics.\nfunc (s *Stack) Statistics(stat interface{}, arg string) error {\nswitch stats := stat.(type) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/protocol.go",
"new_path": "pkg/tcpip/transport/tcp/protocol.go",
"diff": "@@ -80,6 +80,25 @@ const (\n// enable/disable SACK support in TCP. See: https://tools.ietf.org/html/rfc2018.\ntype SACKEnabled bool\n+// Recovery is used by stack.(*Stack).TransportProtocolOption to\n+// set loss detection algorithm in TCP.\n+type Recovery int32\n+\n+const (\n+ // RACKLossDetection indicates RACK is used for loss detection and\n+ // recovery.\n+ RACKLossDetection Recovery = 1 << iota\n+\n+ // RACKStaticReoWnd indicates the reordering window should not be\n+ // adjusted when DSACK is received.\n+ RACKStaticReoWnd\n+\n+ // RACKNoDupTh indicates RACK should not consider the classic three\n+ // duplicate acknowledgements rule to mark the segments as lost. This\n+ // is used when reordering is not detected.\n+ RACKNoDupTh\n+)\n+\n// DelayEnabled is used by stack.(Stack*).TransportProtocolOption to\n// enable/disable Nagle's algorithm in TCP.\ntype DelayEnabled bool\n@@ -161,6 +180,7 @@ func (s *synRcvdCounter) Threshold() uint64 {\ntype protocol struct {\nmu sync.RWMutex\nsackEnabled bool\n+ recovery Recovery\ndelayEnabled bool\nsendBufferSize SendBufferSizeOption\nrecvBufferSize ReceiveBufferSizeOption\n@@ -280,6 +300,12 @@ func (p *protocol) SetOption(option interface{}) *tcpip.Error {\np.mu.Unlock()\nreturn nil\n+ case Recovery:\n+ p.mu.Lock()\n+ p.recovery = Recovery(v)\n+ p.mu.Unlock()\n+ return nil\n+\ncase DelayEnabled:\np.mu.Lock()\np.delayEnabled = bool(v)\n@@ -394,6 +420,12 @@ func (p *protocol) Option(option interface{}) *tcpip.Error {\np.mu.RUnlock()\nreturn nil\n+ case *Recovery:\n+ p.mu.RLock()\n+ *v = Recovery(p.recovery)\n+ p.mu.RUnlock()\n+ return nil\n+\ncase *DelayEnabled:\np.mu.RLock()\n*v = DelayEnabled(p.delayEnabled)\n@@ -535,6 +567,7 @@ func NewProtocol() stack.TransportProtocol {\nminRTO: MinRTO,\nmaxRTO: MaxRTO,\nmaxRetries: MaxRetries,\n+ recovery: RACKLossDetection,\n}\np.dispatcher.init(runtime.GOMAXPROCS(0))\nreturn &p\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/proc_net.cc",
"new_path": "test/syscalls/linux/proc_net.cc",
"diff": "@@ -477,6 +477,44 @@ TEST(ProcNetSnmp, CheckSnmp) {\nEXPECT_EQ(value_count, 1);\n}\n+TEST(ProcSysNetIpv4Recovery, Exists) {\n+ EXPECT_THAT(open(\"/proc/sys/net/ipv4/tcp_recovery\", O_RDONLY),\n+ SyscallSucceeds());\n+}\n+\n+TEST(ProcSysNetIpv4Recovery, CanReadAndWrite) {\n+ // TODO(b/162988252): Enable save/restore for this test after the bug is\n+ // fixed.\n+ DisableSave ds;\n+\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability((CAP_DAC_OVERRIDE))));\n+\n+ auto const fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(\"/proc/sys/net/ipv4/tcp_recovery\", O_RDWR));\n+\n+ char buf[10] = {'\\0'};\n+ char to_write = '2';\n+\n+ // Check initial value is set to 1.\n+ EXPECT_THAT(PreadFd(fd.get(), &buf, sizeof(buf), 0),\n+ SyscallSucceedsWithValue(sizeof(to_write) + 1));\n+ EXPECT_EQ(strcmp(buf, \"1\\n\"), 0);\n+\n+ // Set tcp_recovery to one of the allowed constants.\n+ EXPECT_THAT(PwriteFd(fd.get(), &to_write, sizeof(to_write), 0),\n+ SyscallSucceedsWithValue(sizeof(to_write)));\n+ EXPECT_THAT(PreadFd(fd.get(), &buf, sizeof(buf), 0),\n+ SyscallSucceedsWithValue(sizeof(to_write) + 1));\n+ EXPECT_EQ(strcmp(buf, \"2\\n\"), 0);\n+\n+ // Set tcp_recovery to any random value.\n+ char kMessage[] = \"100\";\n+ EXPECT_THAT(PwriteFd(fd.get(), kMessage, strlen(kMessage), 0),\n+ SyscallSucceedsWithValue(strlen(kMessage)));\n+ EXPECT_THAT(PreadFd(fd.get(), buf, sizeof(kMessage), 0),\n+ SyscallSucceedsWithValue(sizeof(kMessage)));\n+ EXPECT_EQ(strcmp(buf, \"100\\n\"), 0);\n+}\n} // namespace\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add loss recovery option for TCP.
/proc/sys/net/ipv4/tcp_recovery is used to enable RACK loss
recovery in TCP.
PiperOrigin-RevId: 325157807 |
260,004 | 06.08.2020 01:29:32 | 25,200 | fc4dd3ef455975a033714052b12ebebc85e937d5 | Join IPv4 all-systems group on NIC enable
Test:
stack_test.TestJoinLeaveMulticastOnNICEnableDisable
integration_test.TestIncomingMulticastAndBroadcast | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/ipv4.go",
"new_path": "pkg/tcpip/header/ipv4.go",
"diff": "@@ -101,6 +101,11 @@ const (\n// IPv4Version is the version of the ipv4 protocol.\nIPv4Version = 4\n+ // IPv4AllSystems is the all systems IPv4 multicast address as per\n+ // IANA's IPv4 Multicast Address Space Registry. See\n+ // https://www.iana.org/assignments/multicast-addresses/multicast-addresses.xhtml.\n+ IPv4AllSystems tcpip.Address = \"\\xe0\\x00\\x00\\x01\"\n+\n// IPv4Broadcast is the broadcast address of the IPv4 procotol.\nIPv4Broadcast tcpip.Address = \"\\xff\\xff\\xff\\xff\"\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/ndp_test.go",
"new_path": "pkg/tcpip/stack/ndp_test.go",
"diff": "@@ -1689,13 +1689,7 @@ func containsV6Addr(list []tcpip.ProtocolAddress, item tcpip.AddressWithPrefix)\nAddressWithPrefix: item,\n}\n- for _, i := range list {\n- if i == protocolAddress {\n- return true\n- }\n- }\n-\n- return false\n+ return containsAddr(list, protocolAddress)\n}\n// TestNoAutoGenAddr tests that SLAAC is not performed when configured not to.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -217,6 +217,11 @@ func (n *NIC) disableLocked() *tcpip.Error {\n}\nif _, ok := n.stack.networkProtocols[header.IPv4ProtocolNumber]; ok {\n+ // The NIC may have already left the multicast group.\n+ if err := n.leaveGroupLocked(header.IPv4AllSystems, false /* force */); err != nil && err != tcpip.ErrBadLocalAddress {\n+ return err\n+ }\n+\n// The address may have already been removed.\nif err := n.removePermanentAddressLocked(ipv4BroadcastAddr.AddressWithPrefix.Address); err != nil && err != tcpip.ErrBadLocalAddress {\nreturn err\n@@ -255,6 +260,13 @@ func (n *NIC) enable() *tcpip.Error {\nif _, err := n.addAddressLocked(ipv4BroadcastAddr, NeverPrimaryEndpoint, permanent, static, false /* deprecated */); err != nil {\nreturn err\n}\n+\n+ // As per RFC 1122 section 3.3.7, all hosts should join the all-hosts\n+ // multicast group. Note, the IANA calls the all-hosts multicast group the\n+ // all-systems multicast group.\n+ if err := n.joinGroupLocked(header.IPv4ProtocolNumber, header.IPv4AllSystems); err != nil {\n+ return err\n+ }\n}\n// Join the IPv6 All-Nodes Multicast group if the stack is configured to\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -277,6 +277,17 @@ func (l *linkEPWithMockedAttach) isAttached() bool {\nreturn l.attached\n}\n+// Checks to see if list contains an address.\n+func containsAddr(list []tcpip.ProtocolAddress, item tcpip.ProtocolAddress) bool {\n+ for _, i := range list {\n+ if i == item {\n+ return true\n+ }\n+ }\n+\n+ return false\n+}\n+\nfunc TestNetworkReceive(t *testing.T) {\n// Create a stack with the fake network protocol, one nic, and two\n// addresses attached to it: 1 & 2.\n@@ -3089,6 +3100,13 @@ func TestIPv6SourceAddressSelectionScopeAndSameAddress(t *testing.T) {\nfunc TestAddRemoveIPv4BroadcastAddressOnNICEnableDisable(t *testing.T) {\nconst nicID = 1\n+ broadcastAddr := tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: tcpip.AddressWithPrefix{\n+ Address: header.IPv4Broadcast,\n+ PrefixLen: 32,\n+ },\n+ }\ne := loopback.New()\ns := stack.New(stack.Options{\n@@ -3099,49 +3117,41 @@ func TestAddRemoveIPv4BroadcastAddressOnNICEnableDisable(t *testing.T) {\nt.Fatalf(\"CreateNIC(%d, _, %+v) = %s\", nicID, nicOpts, err)\n}\n+ {\nallStackAddrs := s.AllAddresses()\n- allNICAddrs, ok := allStackAddrs[nicID]\n- if !ok {\n+ if allNICAddrs, ok := allStackAddrs[nicID]; !ok {\nt.Fatalf(\"entry for %d missing from allStackAddrs = %+v\", nicID, allStackAddrs)\n+ } else if containsAddr(allNICAddrs, broadcastAddr) {\n+ t.Fatalf(\"got allNICAddrs = %+v, don't want = %+v\", allNICAddrs, broadcastAddr)\n}\n- if l := len(allNICAddrs); l != 0 {\n- t.Fatalf(\"got len(allNICAddrs) = %d, want = 0\", l)\n}\n// Enabling the NIC should add the IPv4 broadcast address.\nif err := s.EnableNIC(nicID); err != nil {\nt.Fatalf(\"s.EnableNIC(%d): %s\", nicID, err)\n}\n- allStackAddrs = s.AllAddresses()\n- allNICAddrs, ok = allStackAddrs[nicID]\n- if !ok {\n+\n+ {\n+ allStackAddrs := s.AllAddresses()\n+ if allNICAddrs, ok := allStackAddrs[nicID]; !ok {\nt.Fatalf(\"entry for %d missing from allStackAddrs = %+v\", nicID, allStackAddrs)\n+ } else if !containsAddr(allNICAddrs, broadcastAddr) {\n+ t.Fatalf(\"got allNICAddrs = %+v, want = %+v\", allNICAddrs, broadcastAddr)\n}\n- if l := len(allNICAddrs); l != 1 {\n- t.Fatalf(\"got len(allNICAddrs) = %d, want = 1\", l)\n- }\n- want := tcpip.ProtocolAddress{\n- Protocol: header.IPv4ProtocolNumber,\n- AddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: header.IPv4Broadcast,\n- PrefixLen: 32,\n- },\n- }\n- if allNICAddrs[0] != want {\n- t.Fatalf(\"got allNICAddrs[0] = %+v, want = %+v\", allNICAddrs[0], want)\n}\n// Disabling the NIC should remove the IPv4 broadcast address.\nif err := s.DisableNIC(nicID); err != nil {\nt.Fatalf(\"s.DisableNIC(%d): %s\", nicID, err)\n}\n- allStackAddrs = s.AllAddresses()\n- allNICAddrs, ok = allStackAddrs[nicID]\n- if !ok {\n+\n+ {\n+ allStackAddrs := s.AllAddresses()\n+ if allNICAddrs, ok := allStackAddrs[nicID]; !ok {\nt.Fatalf(\"entry for %d missing from allStackAddrs = %+v\", nicID, allStackAddrs)\n+ } else if containsAddr(allNICAddrs, broadcastAddr) {\n+ t.Fatalf(\"got allNICAddrs = %+v, don't want = %+v\", allNICAddrs, broadcastAddr)\n}\n- if l := len(allNICAddrs); l != 0 {\n- t.Fatalf(\"got len(allNICAddrs) = %d, want = 0\", l)\n}\n}\n@@ -3189,50 +3199,93 @@ func TestLeaveIPv6SolicitedNodeAddrBeforeAddrRemoval(t *testing.T) {\n}\n}\n-func TestJoinLeaveAllNodesMulticastOnNICEnableDisable(t *testing.T) {\n+func TestJoinLeaveMulticastOnNICEnableDisable(t *testing.T) {\nconst nicID = 1\n+ tests := []struct {\n+ name string\n+ proto tcpip.NetworkProtocolNumber\n+ addr tcpip.Address\n+ }{\n+ {\n+ name: \"IPv6 All-Nodes\",\n+ proto: header.IPv6ProtocolNumber,\n+ addr: header.IPv6AllNodesMulticastAddress,\n+ },\n+ {\n+ name: \"IPv4 All-Systems\",\n+ proto: header.IPv4ProtocolNumber,\n+ addr: header.IPv4AllSystems,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\ne := loopback.New()\ns := stack.New(stack.Options{\n- NetworkProtocols: []stack.NetworkProtocol{ipv6.NewProtocol()},\n+ NetworkProtocols: []stack.NetworkProtocol{ipv4.NewProtocol(), ipv6.NewProtocol()},\n})\nnicOpts := stack.NICOptions{Disabled: true}\nif err := s.CreateNICWithOptions(nicID, e, nicOpts); err != nil {\nt.Fatalf(\"CreateNIC(%d, _, %+v) = %s\", nicID, nicOpts, err)\n}\n- // Should not be in the IPv6 all-nodes multicast group yet because the NIC has\n- // not been enabled yet.\n- isInGroup, err := s.IsInGroup(nicID, header.IPv6AllNodesMulticastAddress)\n- if err != nil {\n- t.Fatalf(\"IsInGroup(%d, %s): %s\", nicID, header.IPv6AllNodesMulticastAddress, err)\n+ // Should not be in the multicast group yet because the NIC has not been\n+ // enabled yet.\n+ if isInGroup, err := s.IsInGroup(nicID, test.addr); err != nil {\n+ t.Fatalf(\"IsInGroup(%d, %s): %s\", nicID, test.addr, err)\n+ } else if isInGroup {\n+ t.Fatalf(\"got IsInGroup(%d, %s) = true, want = false\", nicID, test.addr)\n}\n- if isInGroup {\n- t.Fatalf(\"got IsInGroup(%d, %s) = true, want = false\", nicID, header.IPv6AllNodesMulticastAddress)\n+\n+ // The all-nodes multicast group should be joined when the NIC is enabled.\n+ if err := s.EnableNIC(nicID); err != nil {\n+ t.Fatalf(\"s.EnableNIC(%d): %s\", nicID, err)\n+ }\n+\n+ if isInGroup, err := s.IsInGroup(nicID, test.addr); err != nil {\n+ t.Fatalf(\"IsInGroup(%d, %s): %s\", nicID, test.addr, err)\n+ } else if !isInGroup {\n+ t.Fatalf(\"got IsInGroup(%d, %s) = false, want = true\", nicID, test.addr)\n+ }\n+\n+ // The multicast group should be left when the NIC is disabled.\n+ if err := s.DisableNIC(nicID); err != nil {\n+ t.Fatalf(\"s.DisableNIC(%d): %s\", nicID, err)\n+ }\n+\n+ if isInGroup, err := s.IsInGroup(nicID, test.addr); err != nil {\n+ t.Fatalf(\"IsInGroup(%d, %s): %s\", nicID, test.addr, err)\n+ } else if isInGroup {\n+ t.Fatalf(\"got IsInGroup(%d, %s) = true, want = false\", nicID, test.addr)\n}\n// The all-nodes multicast group should be joined when the NIC is enabled.\nif err := s.EnableNIC(nicID); err != nil {\nt.Fatalf(\"s.EnableNIC(%d): %s\", nicID, err)\n}\n- isInGroup, err = s.IsInGroup(nicID, header.IPv6AllNodesMulticastAddress)\n- if err != nil {\n- t.Fatalf(\"IsInGroup(%d, %s): %s\", nicID, header.IPv6AllNodesMulticastAddress, err)\n+\n+ if isInGroup, err := s.IsInGroup(nicID, test.addr); err != nil {\n+ t.Fatalf(\"IsInGroup(%d, %s): %s\", nicID, test.addr, err)\n+ } else if !isInGroup {\n+ t.Fatalf(\"got IsInGroup(%d, %s) = false, want = true\", nicID, test.addr)\n}\n- if !isInGroup {\n- t.Fatalf(\"got IsInGroup(%d, %s) = false, want = true\", nicID, header.IPv6AllNodesMulticastAddress)\n+\n+ // Leaving the group before disabling the NIC should not cause an error.\n+ if err := s.LeaveGroup(test.proto, nicID, test.addr); err != nil {\n+ t.Fatalf(\"s.LeaveGroup(%d, %d, %s): %s\", test.proto, nicID, test.addr, err)\n}\n- // The all-nodes multicast group should be left when the NIC is disabled.\nif err := s.DisableNIC(nicID); err != nil {\nt.Fatalf(\"s.DisableNIC(%d): %s\", nicID, err)\n}\n- isInGroup, err = s.IsInGroup(nicID, header.IPv6AllNodesMulticastAddress)\n- if err != nil {\n- t.Fatalf(\"IsInGroup(%d, %s): %s\", nicID, header.IPv6AllNodesMulticastAddress, err)\n+\n+ if isInGroup, err := s.IsInGroup(nicID, test.addr); err != nil {\n+ t.Fatalf(\"IsInGroup(%d, %s): %s\", nicID, test.addr, err)\n+ } else if isInGroup {\n+ t.Fatalf(\"got IsInGroup(%d, %s) = true, want = false\", nicID, test.addr)\n}\n- if isInGroup {\n- t.Fatalf(\"got IsInGroup(%d, %s) = true, want = false\", nicID, header.IPv6AllNodesMulticastAddress)\n+ })\n}\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": "@@ -31,7 +31,9 @@ import (\nconst defaultMTU = 1280\n-func TestIncomingSubnetBroadcast(t *testing.T) {\n+// TestIncomingMulticastAndBroadcast tests receiving a packet destined to some\n+// multicast or broadcast address.\n+func TestIncomingMulticastAndBroadcast(t *testing.T) {\nconst (\nnicID = 1\nremotePort = 5555\n@@ -179,6 +181,24 @@ func TestIncomingSubnetBroadcast(t *testing.T) {\nexpectRx: true,\n},\n+ {\n+ name: \"IPv4 all-systems multicast binding to all-systems multicast\",\n+ bindAddr: header.IPv4AllSystems,\n+ dstAddr: header.IPv4AllSystems,\n+ expectRx: true,\n+ },\n+ {\n+ name: \"IPv4 all-systems multicast binding to wildcard\",\n+ dstAddr: header.IPv4AllSystems,\n+ expectRx: true,\n+ },\n+ {\n+ name: \"IPv4 all-systems multicast binding to unicast\",\n+ bindAddr: ipv4Addr.Address,\n+ dstAddr: header.IPv4AllSystems,\n+ expectRx: false,\n+ },\n+\n// IPv6 has no notion of a broadcast.\n{\nname: \"IPv6 unicast binding to wildcard\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/BUILD",
"new_path": "test/packetimpact/tests/BUILD",
"diff": "@@ -40,8 +40,6 @@ packetimpact_go_test(\npacketimpact_go_test(\nname = \"udp_recv_mcast_bcast\",\nsrcs = [\"udp_recv_mcast_bcast_test.go\"],\n- # TODO(b/152813495): Fix netstack then remove the line below.\n- expect_netstack_failure = True,\ndeps = [\n\"//pkg/tcpip\",\n\"//pkg/tcpip/header\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | Join IPv4 all-systems group on NIC enable
Test:
- stack_test.TestJoinLeaveMulticastOnNICEnableDisable
- integration_test.TestIncomingMulticastAndBroadcast
PiperOrigin-RevId: 325185259 |
259,860 | 06.08.2020 11:01:13 | 25,200 | 63447e5afae62dab64940054372166dab45a057c | Only register /dev/net/tun if supported. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/devices/tundev/tundev.go",
"new_path": "pkg/sentry/devices/tundev/tundev.go",
"diff": "@@ -160,8 +160,8 @@ func (fd *tunFD) EventUnregister(e *waiter.Entry) {\nfd.device.EventUnregister(e)\n}\n-// isNetTunSupported returns whether /dev/net/tun device is supported for s.\n-func isNetTunSupported(s inet.Stack) bool {\n+// IsNetTunSupported returns whether /dev/net/tun device is supported for s.\n+func IsNetTunSupported(s inet.Stack) bool {\n_, ok := s.(*netstack.Stack)\nreturn ok\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/vfs.go",
"new_path": "runsc/boot/vfs.go",
"diff": "@@ -37,6 +37,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/proc\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/sys\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/tmpfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/inet\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n@@ -89,6 +90,12 @@ func registerFilesystems(k *kernel.Kernel) error {\nif err := ttydev.Register(vfsObj); err != nil {\nreturn fmt.Errorf(\"registering ttydev: %w\", err)\n}\n+ tunSupported := tundev.IsNetTunSupported(inet.StackFromContext(ctx))\n+ if tunSupported {\n+ if err := tundev.Register(vfsObj); err != nil {\n+ return fmt.Errorf(\"registering tundev: %v\", err)\n+ }\n+ }\nif kernel.FUSEEnabled {\nif err := fuse.Register(vfsObj); err != nil {\n@@ -96,9 +103,6 @@ func registerFilesystems(k *kernel.Kernel) error {\n}\n}\n- if err := tundev.Register(vfsObj); err != nil {\n- return fmt.Errorf(\"registering tundev: %v\", err)\n- }\na, err := devtmpfs.NewAccessor(ctx, vfsObj, creds, devtmpfs.Name)\nif err != nil {\nreturn fmt.Errorf(\"creating devtmpfs accessor: %w\", err)\n@@ -114,9 +118,11 @@ func registerFilesystems(k *kernel.Kernel) error {\nif err := ttydev.CreateDevtmpfsFiles(ctx, a); err != nil {\nreturn fmt.Errorf(\"creating ttydev devtmpfs files: %w\", err)\n}\n+ if tunSupported {\nif err := tundev.CreateDevtmpfsFiles(ctx, a); err != nil {\nreturn fmt.Errorf(\"creating tundev devtmpfs files: %v\", err)\n}\n+ }\nif kernel.FUSEEnabled {\nif err := fuse.CreateDevtmpfsFile(ctx, a); err != nil {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Only register /dev/net/tun if supported.
PiperOrigin-RevId: 325266487 |
259,984 | 05.08.2020 18:29:59 | 0 | 92c06435874434836973d478ba469bc8f5aca356 | add stub go marshallable implementation | [
{
"change_type": "MODIFY",
"old_path": "tools/go_marshal/marshal/BUILD",
"new_path": "tools/go_marshal/marshal/BUILD",
"diff": "@@ -6,6 +6,7 @@ go_library(\nname = \"marshal\",\nsrcs = [\n\"marshal.go\",\n+ \"marshal_impl_util.go\",\n],\nvisibility = [\n\"//:sandbox\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/go_marshal/marshal/marshal_impl_util.go",
"diff": "+// Copyright 2020 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 marshal\n+\n+import (\n+ \"io\"\n+\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+)\n+\n+// StubMarshallable implements the Marshallable interface.\n+// StubMarshallable is a convenient embeddable type for satisfying the\n+// marshallable interface, but provides no actual implementation. It is\n+// useful when the marshallable interface needs to be implemented manually,\n+// but the caller doesn't require the full marshallable interface.\n+type StubMarshallable struct{}\n+\n+// WriteTo implements Marshallable.WriteTo.\n+func (StubMarshallable) WriteTo(w io.Writer) (n int64, err error) {\n+ panic(\"Please implement your own WriteTo function\")\n+}\n+\n+// SizeBytes implements Marshallable.SizeBytes.\n+func (StubMarshallable) SizeBytes() int {\n+ panic(\"Please implement your own SizeBytes function\")\n+}\n+\n+// MarshalBytes implements Marshallable.MarshalBytes.\n+func (StubMarshallable) MarshalBytes(dst []byte) {\n+ panic(\"Please implement your own MarshalBytes function\")\n+}\n+\n+// UnmarshalBytes implements Marshallable.UnmarshalBytes.\n+func (StubMarshallable) UnmarshalBytes(src []byte) {\n+ panic(\"Please implement your own UnMarshalBytes function\")\n+}\n+\n+// Packed implements Marshallable.Packed.\n+func (StubMarshallable) Packed() bool {\n+ panic(\"Please implement your own Packed function\")\n+}\n+\n+// MarshalUnsafe implements Marshallable.MarshalUnsafe.\n+func (StubMarshallable) MarshalUnsafe(dst []byte) {\n+ panic(\"Please implement your own MarshalUnsafe function\")\n+}\n+\n+// UnmarshalUnsafe implements Marshallable.UnmarshalUnsafe.\n+func (StubMarshallable) UnmarshalUnsafe(src []byte) {\n+ panic(\"Please implement your own UnmarshalUnsafe function\")\n+}\n+\n+// CopyIn implements Marshallable.CopyIn.\n+func (StubMarshallable) CopyIn(task Task, addr usermem.Addr) (int, error) {\n+ panic(\"Please implement your own CopyIn function\")\n+}\n+\n+// CopyOut implements Marshallable.CopyOut.\n+func (StubMarshallable) CopyOut(task Task, addr usermem.Addr) (int, error) {\n+ panic(\"Please implement your own CopyOut function\")\n+}\n+\n+// CopyOutN implements Marshallable.CopyOutN.\n+func (StubMarshallable) CopyOutN(task Task, addr usermem.Addr, limit int) (int, error) {\n+ panic(\"Please implement your own CopyOutN function\")\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | add stub go marshallable implementation |
259,992 | 06.08.2020 18:13:55 | 25,200 | f20e63e31b56784c596897e86f03441f9d05f567 | Add LinkAt support to gofer
Updates | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/basic/linktest/Dockerfile",
"diff": "+FROM ubuntu:bionic\n+\n+WORKDIR /root\n+COPY . .\n+\n+RUN apt-get update && apt-get install -y gcc\n+RUN gcc -O2 -o link_test link_test.c\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/basic/linktest/link_test.c",
"diff": "+// Copyright 2020 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 <err.h>\n+#include <fcntl.h>\n+#include <string.h>\n+#include <sys/stat.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+// Basic test for linkat(2). Syscall tests requires CAP_DAC_READ_SEARCH and it\n+// cannot use tricks like userns as root. For this reason, run a basic link test\n+// to ensure some coverage.\n+int main(int argc, char** argv) {\n+ const char kOldPath[] = \"old.txt\";\n+ int fd = open(kOldPath, O_RDWR | O_CREAT | O_TRUNC, 0600);\n+ if (fd < 0) {\n+ errx(1, \"open(%s) failed\", kOldPath);\n+ }\n+ const char kData[] = \"some random content\";\n+ if (write(fd, kData, sizeof(kData)) < 0) {\n+ err(1, \"write failed\");\n+ }\n+ close(fd);\n+\n+ struct stat old_stat;\n+ if (stat(kOldPath, &old_stat)) {\n+ errx(1, \"stat(%s) failed\", kOldPath);\n+ }\n+\n+ const char kNewPath[] = \"new.txt\";\n+ if (link(kOldPath, kNewPath)) {\n+ errx(1, \"link(%s, %s) failed\", kOldPath, kNewPath);\n+ }\n+\n+ struct stat new_stat;\n+ if (stat(kNewPath, &new_stat)) {\n+ errx(1, \"stat(%s) failed\", kNewPath);\n+ }\n+\n+ // Check that files are the same.\n+ if (old_stat.st_dev != new_stat.st_dev) {\n+ errx(1, \"files st_dev is different, want: %lu, got: %lu\", old_stat.st_dev,\n+ new_stat.st_dev);\n+ }\n+ if (old_stat.st_ino != new_stat.st_ino) {\n+ errx(1, \"files st_ino is different, want: %lu, got: %lu\", old_stat.st_ino,\n+ new_stat.st_ino);\n+ }\n+\n+ // Check that link count is correct.\n+ if (new_stat.st_nlink != old_stat.st_nlink + 1) {\n+ errx(1, \"wrong nlink, want: %lu, got: %lu\", old_stat.st_nlink + 1,\n+ new_stat.st_nlink);\n+ }\n+\n+ // Check taht contents are the same.\n+ fd = open(kNewPath, O_RDONLY);\n+ if (fd < 0) {\n+ errx(1, \"open(%s) failed\", kNewPath);\n+ }\n+ char buf[sizeof(kData)] = {};\n+ if (read(fd, buf, sizeof(buf)) < 0) {\n+ err(1, \"read failed\");\n+ }\n+ close(fd);\n+\n+ if (strcmp(buf, kData) != 0) {\n+ errx(1, \"file content mismatch: %s\", buf);\n+ }\n+\n+ // Cleanup.\n+ if (unlink(kNewPath)) {\n+ errx(1, \"unlink(%s) failed\", kNewPath);\n+ }\n+ if (unlink(kOldPath)) {\n+ errx(1, \"unlink(%s) failed\", kOldPath);\n+ }\n+\n+ // Success!\n+ return 0;\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"new_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"diff": "package gofer\nimport (\n+ \"math\"\n\"sync\"\n\"sync/atomic\"\n@@ -724,8 +725,29 @@ func (fs *filesystem) LinkAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.\nif rp.Mount() != vd.Mount() {\nreturn syserror.EXDEV\n}\n- // 9P2000.L supports hard links, but we don't.\n+ d := vd.Dentry().Impl().(*dentry)\n+ if d.isDir() {\nreturn syserror.EPERM\n+ }\n+ gid := auth.KGID(atomic.LoadUint32(&d.gid))\n+ uid := auth.KUID(atomic.LoadUint32(&d.uid))\n+ mode := linux.FileMode(atomic.LoadUint32(&d.mode))\n+ if err := vfs.MayLink(rp.Credentials(), mode, uid, gid); err != nil {\n+ return err\n+ }\n+ if d.nlink == 0 {\n+ return syserror.ENOENT\n+ }\n+ if d.nlink == math.MaxUint32 {\n+ return syserror.EMLINK\n+ }\n+ if err := parent.file.link(ctx, d.file, childName); err != nil {\n+ return err\n+ }\n+\n+ // Success!\n+ atomic.AddUint32(&d.nlink, 1)\n+ return nil\n}, nil)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -558,8 +558,6 @@ type dentry struct {\n// filesystem.renameMu.\nname string\n- // We don't support hard links, so each dentry maps 1:1 to an inode.\n-\n// file is the unopened p9.File that backs this dentry. file is immutable.\n//\n// If file.isNil(), this dentry represents a synthetic file, i.e. a file\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/docker_tests.sh",
"new_path": "scripts/docker_tests.sh",
"diff": "@@ -23,5 +23,5 @@ test_runsc //test/image:image_test //test/e2e:integration_test\ninstall_runsc_for_test docker --vfs2\nIMAGE_FILTER=\"Hello|Httpd|Ruby|Stdio\"\n-INTEGRATION_FILTER=\"LifeCycle|Pause|Connect|JobControl|Overlay|Exec|DirCreation/root\"\n+INTEGRATION_FILTER=\"LifeCycle|Pause|Connect|JobControl|Overlay|Exec|DirCreation/root|Link\"\ntest_runsc //test/e2e:integration_test //test/image:image_test --test_filter=\"${IMAGE_FILTER}|${INTEGRATION_FILTER}\"\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/integration_test.go",
"new_path": "test/e2e/integration_test.go",
"diff": "@@ -467,6 +467,24 @@ func TestHostOverlayfsRewindDir(t *testing.T) {\n}\n}\n+// Basic test for linkat(2). Syscall tests requires CAP_DAC_READ_SEARCH and it\n+// cannot use tricks like userns as root. For this reason, run a basic link test\n+// to ensure some coverage.\n+func TestLink(t *testing.T) {\n+ ctx := context.Background()\n+ d := dockerutil.MakeContainer(ctx, t)\n+ defer d.CleanUp(ctx)\n+\n+ if got, err := d.Run(ctx, dockerutil.RunOpts{\n+ Image: \"basic/linktest\",\n+ WorkDir: \"/root\",\n+ }, \"./link_test\"); err != nil {\n+ t.Fatalf(\"docker run failed: %v\", err)\n+ } else if got != \"\" {\n+ t.Errorf(\"test failed:\\n%s\", got)\n+ }\n+}\n+\nfunc TestMain(m *testing.M) {\ndockerutil.EnsureSupportedDockerVersion()\nflag.Parse()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add LinkAt support to gofer
Updates #1198
PiperOrigin-RevId: 325350818 |
259,885 | 07.08.2020 00:10:35 | 25,200 | 4fa1c304a133297bc6895729d74aa35a015e759e | Try to update atime and mtime on VFS2 gofer files on dentry eviction. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -192,10 +192,14 @@ const (\n//\n// - File timestamps are based on client clocks. This ensures that users of\n// the client observe timestamps that are coherent with their own clocks\n- // and consistent with Linux's semantics. However, since it is not always\n- // possible for clients to set arbitrary atimes and mtimes, and never\n- // possible for clients to set arbitrary ctimes, file timestamp changes are\n- // stored in the client only and never sent to the remote filesystem.\n+ // and consistent with Linux's semantics (in particular, it is not always\n+ // possible for clients to set arbitrary atimes and mtimes depending on the\n+ // remote filesystem implementation, and never possible for clients to set\n+ // arbitrary ctimes.) If a dentry containing a client-defined atime or\n+ // mtime is evicted from cache, client timestamps will be sent to the\n+ // remote filesystem on a best-effort basis to attempt to ensure that\n+ // timestamps will be preserved when another dentry representing the same\n+ // file is instantiated.\nInteropModeExclusive InteropMode = iota\n// InteropModeWritethrough is appropriate when there are read-only users of\n@@ -621,6 +625,12 @@ type dentry struct {\n// File size, protected by both metadataMu and dataMu (i.e. both must be\n// locked to mutate it; locking either is sufficient to access it).\nsize uint64\n+ // If this dentry does not represent a synthetic file, deleted is 0, and\n+ // atimeDirty/mtimeDirty are non-zero, atime/mtime may have diverged from the\n+ // remote file's timestamps, which should be updated when this dentry is\n+ // evicted.\n+ atimeDirty uint32\n+ mtimeDirty uint32\n// nlink counts the number of hard links to this dentry. It's updated and\n// accessed using atomic operations. It's not protected by metadataMu like the\n@@ -801,10 +811,12 @@ func (d *dentry) updateFromP9AttrsLocked(mask p9.AttrMask, attr *p9.Attr) {\nif attr.BlockSize != 0 {\natomic.StoreUint32(&d.blockSize, uint32(attr.BlockSize))\n}\n- if mask.ATime {\n+ // Don't override newer client-defined timestamps with old server-defined\n+ // ones.\n+ if mask.ATime && atomic.LoadUint32(&d.atimeDirty) == 0 {\natomic.StoreInt64(&d.atime, dentryTimestampFromP9(attr.ATimeSeconds, attr.ATimeNanoSeconds))\n}\n- if mask.MTime {\n+ if mask.MTime && atomic.LoadUint32(&d.mtimeDirty) == 0 {\natomic.StoreInt64(&d.mtime, dentryTimestampFromP9(attr.MTimeSeconds, attr.MTimeNanoSeconds))\n}\nif mask.CTime {\n@@ -901,51 +913,44 @@ func (d *dentry) setStat(ctx context.Context, creds *auth.Credentials, opts *vfs\nreturn err\n}\ndefer mnt.EndWrite()\n- setLocalAtime := false\n- setLocalMtime := false\n- if d.cachedMetadataAuthoritative() {\n- // Timestamp updates will be handled locally.\n- setLocalAtime = stat.Mask&linux.STATX_ATIME != 0\n- setLocalMtime = stat.Mask&linux.STATX_MTIME != 0\n- stat.Mask &^= linux.STATX_ATIME | linux.STATX_MTIME\n- // Prepare for truncate.\nif stat.Mask&linux.STATX_SIZE != 0 {\n+ // Reject attempts to truncate files other than regular files, since\n+ // filesystem implementations may return the wrong errno.\nswitch mode.FileType() {\n- case linux.ModeRegular:\n- if !setLocalMtime {\n- // Truncate updates mtime.\n- setLocalMtime = true\n- stat.Mtime.Nsec = linux.UTIME_NOW\n- }\n- case linux.ModeDirectory:\n+ case linux.S_IFREG:\n+ // ok\n+ case linux.S_IFDIR:\nreturn syserror.EISDIR\ndefault:\nreturn syserror.EINVAL\n}\n}\n+\n+ var now int64\n+ if d.cachedMetadataAuthoritative() {\n+ // Truncate updates mtime.\n+ if stat.Mask&(linux.STATX_SIZE|linux.STATX_MTIME) == linux.STATX_SIZE {\n+ stat.Mask |= linux.STATX_MTIME\n+ stat.Mtime = linux.StatxTimestamp{\n+ Nsec: linux.UTIME_NOW,\n}\n+ }\n+\n+ // Use client clocks for timestamps.\n+ now = d.fs.clock.Now().Nanoseconds()\n+ if stat.Mask&linux.STATX_ATIME != 0 && stat.Atime.Nsec == linux.UTIME_NOW {\n+ stat.Atime = statxTimestampFromDentry(now)\n+ }\n+ if stat.Mask&linux.STATX_MTIME != 0 && stat.Mtime.Nsec == linux.UTIME_NOW {\n+ stat.Mtime = statxTimestampFromDentry(now)\n+ }\n+ }\n+\nd.metadataMu.Lock()\ndefer d.metadataMu.Unlock()\n- if stat.Mask&linux.STATX_SIZE != 0 {\n- // The size needs to be changed even when\n- // !d.cachedMetadataAuthoritative() because d.mappings has to be\n- // updated.\n- d.updateFileSizeLocked(stat.Size)\n- }\nif !d.isSynthetic() {\nif stat.Mask != 0 {\n- if stat.Mask&linux.STATX_SIZE != 0 {\n- // Check whether to allow a truncate request to be made.\n- switch d.mode & linux.S_IFMT {\n- case linux.S_IFREG:\n- // Allow.\n- case linux.S_IFDIR:\n- return syserror.EISDIR\n- default:\n- return syserror.EINVAL\n- }\n- }\nif err := d.file.setAttr(ctx, p9.SetAttrMask{\nPermissions: stat.Mask&linux.STATX_MODE != 0,\nUID: stat.Mask&linux.STATX_UID != 0,\n@@ -967,6 +972,11 @@ func (d *dentry) setStat(ctx context.Context, creds *auth.Credentials, opts *vfs\n}); err != nil {\nreturn err\n}\n+ if stat.Mask&linux.STATX_SIZE != 0 {\n+ // Privatized copy-on-write mappings of truncated pages need to\n+ // be invalidated even if InteropModeShared is in effect.\n+ d.updateFileSizeLocked(stat.Size)\n+ }\n}\nif d.fs.opts.interop == InteropModeShared {\n// There's no point to updating d's metadata in this case since\n@@ -976,7 +986,6 @@ func (d *dentry) setStat(ctx context.Context, creds *auth.Credentials, opts *vfs\nreturn nil\n}\n}\n- now := d.fs.clock.Now().Nanoseconds()\nif stat.Mask&linux.STATX_MODE != 0 {\natomic.StoreUint32(&d.mode, d.fileType()|uint32(stat.Mode))\n}\n@@ -986,23 +995,18 @@ func (d *dentry) setStat(ctx context.Context, creds *auth.Credentials, opts *vfs\nif stat.Mask&linux.STATX_GID != 0 {\natomic.StoreUint32(&d.gid, stat.GID)\n}\n- if setLocalAtime {\n- if stat.Atime.Nsec == linux.UTIME_NOW {\n- atomic.StoreInt64(&d.atime, now)\n- } else {\n+ // Note that stat.Atime.Nsec and stat.Mtime.Nsec can't be UTIME_NOW because\n+ // if d.cachedMetadataAuthoritative() then we converted stat.Atime and\n+ // stat.Mtime to client-local timestamps above, and if\n+ // !d.cachedMetadataAuthoritative() then we returned after calling\n+ // d.file.setAttr(). For the same reason, now must have been initialized.\n+ if stat.Mask&linux.STATX_ATIME != 0 {\natomic.StoreInt64(&d.atime, dentryTimestampFromStatx(stat.Atime))\n+ atomic.StoreUint32(&d.atimeDirty, 0)\n}\n- // Restore mask bits that we cleared earlier.\n- stat.Mask |= linux.STATX_ATIME\n- }\n- if setLocalMtime {\n- if stat.Mtime.Nsec == linux.UTIME_NOW {\n- atomic.StoreInt64(&d.mtime, now)\n- } else {\n+ if stat.Mask&linux.STATX_MTIME != 0 {\natomic.StoreInt64(&d.mtime, dentryTimestampFromStatx(stat.Mtime))\n- }\n- // Restore mask bits that we cleared earlier.\n- stat.Mask |= linux.STATX_MTIME\n+ atomic.StoreUint32(&d.mtimeDirty, 0)\n}\natomic.StoreInt64(&d.ctime, now)\nreturn nil\n@@ -1248,7 +1252,7 @@ func (d *dentry) destroyLocked(ctx context.Context) {\n// Write dirty pages back to the remote filesystem.\nif d.handleWritable {\nif err := fsutil.SyncDirtyAll(ctx, &d.cache, &d.dirty, d.size, mf, d.handle.writeFromBlocksAt); err != nil {\n- log.Warningf(\"gofer.dentry.DecRef: failed to write dirty data back: %v\", err)\n+ log.Warningf(\"gofer.dentry.destroyLocked: failed to write dirty data back: %v\", err)\n}\n}\n// Discard cached data.\n@@ -1261,6 +1265,28 @@ func (d *dentry) destroyLocked(ctx context.Context) {\nd.handleMu.Unlock()\nif !d.file.isNil() {\n+ if !d.isDeleted() {\n+ // Write dirty timestamps back to the remote filesystem.\n+ atimeDirty := atomic.LoadUint32(&d.atimeDirty) != 0\n+ mtimeDirty := atomic.LoadUint32(&d.mtimeDirty) != 0\n+ if atimeDirty || mtimeDirty {\n+ atime := atomic.LoadInt64(&d.atime)\n+ mtime := atomic.LoadInt64(&d.mtime)\n+ if err := d.file.setAttr(ctx, p9.SetAttrMask{\n+ ATime: atimeDirty,\n+ ATimeNotSystemTime: atimeDirty,\n+ MTime: mtimeDirty,\n+ MTimeNotSystemTime: mtimeDirty,\n+ }, p9.SetAttr{\n+ ATimeSeconds: uint64(atime / 1e9),\n+ ATimeNanoSeconds: uint64(atime % 1e9),\n+ MTimeSeconds: uint64(mtime / 1e9),\n+ MTimeNanoSeconds: uint64(mtime % 1e9),\n+ }); err != nil {\n+ log.Warningf(\"gofer.dentry.destroyLocked: failed to write dirty timestamps back: %v\", err)\n+ }\n+ }\n+ }\nd.file.close(ctx)\nd.file = p9file{}\n// Remove d from the set of syncable dentries.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/time.go",
"new_path": "pkg/sentry/fsimpl/gofer/time.go",
"diff": "@@ -47,6 +47,7 @@ func (d *dentry) touchAtime(mnt *vfs.Mount) {\nnow := d.fs.clock.Now().Nanoseconds()\nd.metadataMu.Lock()\natomic.StoreInt64(&d.atime, now)\n+ atomic.StoreUint32(&d.atimeDirty, 1)\nd.metadataMu.Unlock()\nmnt.EndWrite()\n}\n@@ -67,6 +68,7 @@ func (d *dentry) touchCMtime() {\nd.metadataMu.Lock()\natomic.StoreInt64(&d.mtime, now)\natomic.StoreInt64(&d.ctime, now)\n+ atomic.StoreUint32(&d.mtimeDirty, 1)\nd.metadataMu.Unlock()\n}\n@@ -76,4 +78,5 @@ func (d *dentry) touchCMtimeLocked() {\nnow := d.fs.clock.Now().Nanoseconds()\natomic.StoreInt64(&d.mtime, now)\natomic.StoreInt64(&d.ctime, now)\n+ atomic.StoreUint32(&d.mtimeDirty, 1)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Try to update atime and mtime on VFS2 gofer files on dentry eviction.
PiperOrigin-RevId: 325388385 |
259,885 | 07.08.2020 11:24:09 | 25,200 | 8c1573ebab260a2a40c41265918df3533bd93b3d | Tolerate EINTR from fallocate() in inotify test. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/inotify.cc",
"new_path": "test/syscalls/linux/inotify.cc",
"diff": "@@ -1693,7 +1693,7 @@ TEST(Inotify, Fallocate) {\nInotifyAddWatch(inotify_fd.get(), file.path(), IN_ALL_EVENTS));\n// Do an arbitrary modification with fallocate.\n- ASSERT_THAT(fallocate(fd.get(), 0, 0, 123), SyscallSucceeds());\n+ ASSERT_THAT(RetryEINTR(fallocate)(fd.get(), 0, 0, 123), SyscallSucceeds());\nstd::vector<Event> events =\nASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));\nEXPECT_THAT(events, Are({Event(IN_MODIFY, wd)}));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Tolerate EINTR from fallocate() in inotify test.
PiperOrigin-RevId: 325472312 |
259,853 | 07.08.2020 13:08:51 | 25,200 | 10c13bccaf5ec963b78f5e61629b4528ed9e9c6b | tcp: change the limit of TCP_LINGER2
It was changed in the Linux kernel:
commit
Date: Fri Apr 24 16:06:16 2020 +0800
net: Replace the limit of TCP_LINGER2 with TCP_FIN_TIMEOUT_MAX | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -1777,15 +1777,8 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\n// Same as effectively disabling TCPLinger timeout.\nv = 0\n}\n- var stkTCPLingerTimeout tcpip.TCPLingerTimeoutOption\n- if err := e.stack.TransportProtocolOption(header.TCPProtocolNumber, &stkTCPLingerTimeout); err != nil {\n- // We were unable to retrieve a stack config, just use\n- // the DefaultTCPLingerTimeout.\n- if v > tcpip.TCPLingerTimeoutOption(DefaultTCPLingerTimeout) {\n- stkTCPLingerTimeout = tcpip.TCPLingerTimeoutOption(DefaultTCPLingerTimeout)\n- }\n- }\n- // Cap it to the stack wide TCPLinger timeout.\n+ // Cap it to MaxTCPLingerTimeout.\n+ stkTCPLingerTimeout := tcpip.TCPLingerTimeoutOption(MaxTCPLingerTimeout)\nif v > stkTCPLingerTimeout {\nv = stkTCPLingerTimeout\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/protocol.go",
"new_path": "pkg/tcpip/transport/tcp/protocol.go",
"diff": "@@ -62,6 +62,10 @@ const (\n// FIN_WAIT_2 state before being marked closed.\nDefaultTCPLingerTimeout = 60 * time.Second\n+ // MaxTCPLingerTimeout is the maximum amount of time that sockets\n+ // linger in FIN_WAIT_2 state before being marked closed.\n+ MaxTCPLingerTimeout = 120 * time.Second\n+\n// DefaultTCPTimeWaitTimeout is the amount of time that sockets linger\n// in TIME_WAIT state before being marked closed.\nDefaultTCPTimeWaitTimeout = 60 * time.Second\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"new_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"diff": "@@ -6112,7 +6112,7 @@ func TestTCPLingerTimeout(t *testing.T) {\n{\"InRangeLingerTimeout\", 10 * time.Second, 10 * time.Second},\n// Values > stack's TCPLingerTimeout are capped to the stack's\n// value. Defaults to tcp.DefaultTCPLingerTimeout(60 seconds)\n- {\"AboveMaxLingerTimeout\", 65 * time.Second, 60 * time.Second},\n+ {\"AboveMaxLingerTimeout\", 125 * time.Second, 120 * time.Second},\n}\nfor _, tc := range testCases {\nt.Run(tc.name, func(t *testing.T) {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ip_tcp_generic.cc",
"new_path": "test/syscalls/linux/socket_ip_tcp_generic.cc",
"diff": "namespace gvisor {\nnamespace testing {\n+using ::testing::AnyOf;\n+using ::testing::Eq;\n+\nTEST_P(TCPSocketPairTest, TcpInfoSucceeds) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n@@ -800,6 +803,9 @@ TEST_P(TCPSocketPairTest, SetCongestionControlFailsForUnsupported) {\n// Linux and Netstack both default to a 60s TCP_LINGER2 timeout.\nconstexpr int kDefaultTCPLingerTimeout = 60;\n+// On Linux, the maximum linger2 timeout was changed from 60sec to 120sec.\n+constexpr int kMaxTCPLingerTimeout = 120;\n+constexpr int kOldMaxTCPLingerTimeout = 60;\nTEST_P(TCPSocketPairTest, TCPLingerTimeoutDefault) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n@@ -827,12 +833,12 @@ TEST_P(TCPSocketPairTest, SetTCPLingerTimeoutZeroOrLess) {\nSyscallSucceedsWithValue(0));\n}\n-TEST_P(TCPSocketPairTest, SetTCPLingerTimeoutAboveDefault) {\n+TEST_P(TCPSocketPairTest, SetTCPLingerTimeoutAboveMax) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n// Values above the net.ipv4.tcp_fin_timeout are capped to tcp_fin_timeout\n// on linux (defaults to 60 seconds on linux).\n- constexpr int kAboveDefault = kDefaultTCPLingerTimeout + 1;\n+ constexpr int kAboveDefault = kMaxTCPLingerTimeout + 1;\nEXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_LINGER2,\n&kAboveDefault, sizeof(kAboveDefault)),\nSyscallSucceedsWithValue(0));\n@@ -843,7 +849,12 @@ TEST_P(TCPSocketPairTest, SetTCPLingerTimeoutAboveDefault) {\ngetsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_LINGER2, &get, &get_len),\nSyscallSucceedsWithValue(0));\nEXPECT_EQ(get_len, sizeof(get));\n- EXPECT_EQ(get, kDefaultTCPLingerTimeout);\n+ if (IsRunningOnGvisor()) {\n+ EXPECT_EQ(get, kMaxTCPLingerTimeout);\n+ } else {\n+ EXPECT_THAT(get,\n+ AnyOf(Eq(kMaxTCPLingerTimeout), Eq(kOldMaxTCPLingerTimeout)));\n+ }\n}\nTEST_P(TCPSocketPairTest, SetTCPLingerTimeout) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | tcp: change the limit of TCP_LINGER2
It was changed in the Linux kernel:
commit f0628c524fd188c3f9418e12478dfdfadacba815
Date: Fri Apr 24 16:06:16 2020 +0800
net: Replace the limit of TCP_LINGER2 with TCP_FIN_TIMEOUT_MAX
PiperOrigin-RevId: 325493859 |
259,975 | 07.08.2020 13:28:11 | 25,200 | a7bd0a701289f8d808f93eaded266f6a1bab03ea | Port Startup and Density Benchmarks. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/alpine/Dockerfile",
"diff": "+FROM alpine:latest\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/util/Dockerfile",
"diff": "+FROM ubuntu:bionic\n+\n+RUN apt-get update && apt-get install -y wget\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/base/BUILD",
"new_path": "test/benchmarks/base/BUILD",
"diff": "@@ -5,14 +5,20 @@ package(licenses = [\"notice\"])\ngo_library(\nname = \"base\",\ntestonly = 1,\n- srcs = [\"base.go\"],\n+ srcs = [\n+ \"base.go\",\n+ ],\ndeps = [\"//test/benchmarks/harness\"],\n)\ngo_test(\nname = \"base_test\",\n- size = \"small\",\n- srcs = [\"sysbench_test.go\"],\n+ size = \"large\",\n+ srcs = [\n+ \"size_test.go\",\n+ \"startup_test.go\",\n+ \"sysbench_test.go\",\n+ ],\nlibrary = \":base\",\ntags = [\n# Requires docker and runsc to be configured before test runs.\n@@ -21,6 +27,7 @@ go_test(\n],\ndeps = [\n\"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/harness\",\n\"//test/benchmarks/tools\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/base/base.go",
"new_path": "test/benchmarks/base/base.go",
"diff": "@@ -22,10 +22,10 @@ import (\n\"gvisor.dev/gvisor/test/benchmarks/harness\"\n)\n-var h harness.Harness\n+var testHarness harness.Harness\n// TestMain is the main method for package network.\nfunc TestMain(m *testing.M) {\n- h.Init()\n+ testHarness.Init()\nos.Exit(m.Run())\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/benchmarks/base/size_test.go",
"diff": "+// Copyright 2020 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 base\n+\n+import (\n+ \"context\"\n+ \"testing\"\n+ \"time\"\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+// BenchmarkSizeEmpty creates N empty containers and reads memory usage from\n+// /proc/meminfo.\n+func BenchmarkSizeEmpty(b *testing.B) {\n+ machine, err := testHarness.GetMachine()\n+ if err != nil {\n+ b.Fatalf(\"failed to get machine: %v\", err)\n+ }\n+ defer machine.CleanUp()\n+ meminfo := tools.Meminfo{}\n+ ctx := context.Background()\n+ containers := make([]*dockerutil.Container, 0, b.N)\n+\n+ // DropCaches before the test.\n+ harness.DropCaches(machine)\n+\n+ // Check available memory on 'machine'.\n+ cmd, args := meminfo.MakeCmd()\n+ before, err := machine.RunCommand(cmd, args...)\n+ if err != nil {\n+ b.Fatalf(\"failed to get meminfo: %v\", err)\n+ }\n+\n+ // Make N containers.\n+ for i := 0; i < b.N; i++ {\n+ container := machine.GetContainer(ctx, b)\n+ containers = append(containers, container)\n+ if err := container.Spawn(ctx, dockerutil.RunOpts{\n+ Image: \"benchmarks/alpine\",\n+ }, \"sh\", \"-c\", \"echo Hello && sleep 1000\"); err != nil {\n+ cleanUpContainers(ctx, containers)\n+ b.Fatalf(\"failed to run container: %v\", err)\n+ }\n+ if _, err := container.WaitForOutputSubmatch(ctx, \"Hello\", 5*time.Second); err != nil {\n+ cleanUpContainers(ctx, containers)\n+ b.Fatalf(\"failed to read container output: %v\", err)\n+ }\n+ }\n+\n+ // Drop caches again before second measurement.\n+ harness.DropCaches(machine)\n+\n+ // Check available memory after containers are up.\n+ after, err := machine.RunCommand(cmd, args...)\n+ cleanUpContainers(ctx, containers)\n+ if err != nil {\n+ b.Fatalf(\"failed to get meminfo: %v\", err)\n+ }\n+ meminfo.Report(b, before, after)\n+}\n+\n+// BenchmarkSizeNginx starts N containers running Nginx, checks that they're\n+// serving, and checks memory used based on /proc/meminfo.\n+func BenchmarkSizeNginx(b *testing.B) {\n+ machine, err := testHarness.GetMachine()\n+ if err != nil {\n+ b.Fatalf(\"failed to get machine with: %v\", err)\n+ }\n+ defer machine.CleanUp()\n+\n+ // DropCaches for the first measurement.\n+ harness.DropCaches(machine)\n+\n+ // Measure MemAvailable before creating containers.\n+ meminfo := tools.Meminfo{}\n+ cmd, args := meminfo.MakeCmd()\n+ before, err := machine.RunCommand(cmd, args...)\n+ if err != nil {\n+ b.Fatalf(\"failed to run meminfo command: %v\", err)\n+ }\n+\n+ // Make N Nginx containers.\n+ ctx := context.Background()\n+ runOpts := dockerutil.RunOpts{\n+ Image: \"benchmarks/nginx\",\n+ }\n+ const port = 80\n+ servers := startServers(ctx, b,\n+ serverArgs{\n+ machine: machine,\n+ port: port,\n+ runOpts: runOpts,\n+ })\n+ defer cleanUpContainers(ctx, servers)\n+\n+ // DropCaches after servers are created.\n+ harness.DropCaches(machine)\n+ // Take after measurement.\n+ after, err := machine.RunCommand(cmd, args...)\n+ if err != nil {\n+ b.Fatalf(\"failed to run meminfo command: %v\", err)\n+ }\n+ meminfo.Report(b, before, after)\n+}\n+\n+// BenchmarkSizeNode starts N containers running a Node app, checks that\n+// they're serving, and checks memory used based on /proc/meminfo.\n+func BenchmarkSizeNode(b *testing.B) {\n+ machine, err := testHarness.GetMachine()\n+ if err != nil {\n+ b.Fatalf(\"failed to get machine with: %v\", err)\n+ }\n+ defer machine.CleanUp()\n+\n+ // Make a redis instance for Node to connect.\n+ ctx := context.Background()\n+ redis, redisIP := redisInstance(ctx, b, machine)\n+ defer redis.CleanUp(ctx)\n+\n+ // DropCaches after redis is created.\n+ harness.DropCaches(machine)\n+\n+ // Take before measurement.\n+ meminfo := tools.Meminfo{}\n+ cmd, args := meminfo.MakeCmd()\n+ before, err := machine.RunCommand(cmd, args...)\n+ if err != nil {\n+ b.Fatalf(\"failed to run meminfo commend: %v\", err)\n+ }\n+\n+ // Create N Node servers.\n+ runOpts := dockerutil.RunOpts{\n+ Image: \"benchmarks/node\",\n+ WorkDir: \"/usr/src/app\",\n+ Links: []string{redis.MakeLink(\"redis\")},\n+ }\n+ nodeCmd := []string{\"node\", \"index.js\", redisIP.String()}\n+ const port = 8080\n+ servers := startServers(ctx, b,\n+ serverArgs{\n+ machine: machine,\n+ port: port,\n+ runOpts: runOpts,\n+ cmd: nodeCmd,\n+ })\n+ defer cleanUpContainers(ctx, servers)\n+\n+ // DropCaches after servers are created.\n+ harness.DropCaches(machine)\n+ // Take after measurement.\n+ cmd, args = meminfo.MakeCmd()\n+ after, err := machine.RunCommand(cmd, args...)\n+ if err != nil {\n+ b.Fatalf(\"failed to run meminfo command: %v\", err)\n+ }\n+ meminfo.Report(b, before, after)\n+}\n+\n+// serverArgs wraps args for startServers and runServerWorkload.\n+type serverArgs struct {\n+ machine harness.Machine\n+ port int\n+ runOpts dockerutil.RunOpts\n+ cmd []string\n+}\n+\n+// startServers starts b.N containers defined by 'runOpts' and 'cmd' and uses\n+// 'machine' to check that each is up.\n+func startServers(ctx context.Context, b *testing.B, args serverArgs) []*dockerutil.Container {\n+ b.Helper()\n+ servers := make([]*dockerutil.Container, 0, b.N)\n+\n+ // Create N servers and wait until each of them is serving.\n+ for i := 0; i < b.N; i++ {\n+ server := args.machine.GetContainer(ctx, b)\n+ servers = append(servers, server)\n+ if err := server.Spawn(ctx, args.runOpts, args.cmd...); err != nil {\n+ cleanUpContainers(ctx, servers)\n+ b.Fatalf(\"failed to spawn node instance: %v\", err)\n+ }\n+\n+ // Get the container IP.\n+ servingIP, err := server.FindIP(ctx, false)\n+ if err != nil {\n+ cleanUpContainers(ctx, servers)\n+ b.Fatalf(\"failed to get ip from server: %v\", err)\n+ }\n+\n+ // Wait until the server is up.\n+ if err := harness.WaitUntilServing(ctx, args.machine, servingIP, args.port); err != nil {\n+ cleanUpContainers(ctx, servers)\n+ b.Fatalf(\"failed to wait for serving\")\n+ }\n+ }\n+ return servers\n+}\n+\n+// cleanUpContainers cleans up a slice of containers.\n+func cleanUpContainers(ctx context.Context, containers []*dockerutil.Container) {\n+ for _, c := range containers {\n+ if c != nil {\n+ c.CleanUp(ctx)\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/benchmarks/base/startup_test.go",
"diff": "+// Copyright 2020 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 base\n+\n+import (\n+ \"context\"\n+ \"fmt\"\n+ \"net\"\n+ \"testing\"\n+ \"time\"\n+\n+ \"gvisor.dev/gvisor/pkg/test/dockerutil\"\n+ \"gvisor.dev/gvisor/test/benchmarks/harness\"\n+)\n+\n+// BenchmarkStartEmpty times startup time for an empty container.\n+func BenchmarkStartupEmpty(b *testing.B) {\n+ machine, err := testHarness.GetMachine()\n+ if err != nil {\n+ b.Fatalf(\"failed to get machine: %v\", err)\n+ }\n+ defer machine.CleanUp()\n+\n+ ctx := context.Background()\n+ for i := 0; i < b.N; i++ {\n+ container := machine.GetContainer(ctx, b)\n+ defer container.CleanUp(ctx)\n+ if _, err := container.Run(ctx, dockerutil.RunOpts{\n+ Image: \"benchmarks/alpine\",\n+ }, \"true\"); err != nil {\n+ b.Fatalf(\"failed to run container: %v\", err)\n+ }\n+ }\n+}\n+\n+// BenchmarkStartupNginx times startup for a Nginx instance.\n+// Time is measured from start until the first request is served.\n+func BenchmarkStartupNginx(b *testing.B) {\n+ // The machine to hold Nginx and the Node Server.\n+ machine, err := testHarness.GetMachine()\n+ if err != nil {\n+ b.Fatalf(\"failed to get machine with: %v\", err)\n+ }\n+ defer machine.CleanUp()\n+\n+ ctx := context.Background()\n+ runOpts := dockerutil.RunOpts{\n+ Image: \"benchmarks/nginx\",\n+ }\n+ runServerWorkload(ctx, b,\n+ serverArgs{\n+ machine: machine,\n+ runOpts: runOpts,\n+ port: 80,\n+ })\n+}\n+\n+// BenchmarkStartupNode times startup for a Node application instance.\n+// Time is measured from start until the first request is served.\n+// Note that the Node app connects to a Redis instance before serving.\n+func BenchmarkStartupNode(b *testing.B) {\n+ machine, err := testHarness.GetMachine()\n+ if err != nil {\n+ b.Fatalf(\"failed to get machine with: %v\", err)\n+ }\n+ defer machine.CleanUp()\n+\n+ ctx := context.Background()\n+ redis, redisIP := redisInstance(ctx, b, machine)\n+ defer redis.CleanUp(ctx)\n+ runOpts := dockerutil.RunOpts{\n+ Image: \"benchmarks/node\",\n+ WorkDir: \"/usr/src/app\",\n+ Links: []string{redis.MakeLink(\"redis\")},\n+ }\n+\n+ cmd := []string{\"node\", \"index.js\", redisIP.String()}\n+ runServerWorkload(ctx, b,\n+ serverArgs{\n+ machine: machine,\n+ port: 8080,\n+ runOpts: runOpts,\n+ cmd: cmd,\n+ })\n+}\n+\n+// redisInstance returns a Redis container and its reachable IP.\n+func redisInstance(ctx context.Context, b *testing.B, machine harness.Machine) (*dockerutil.Container, net.IP) {\n+ b.Helper()\n+ // Spawn a redis instance for the app to use.\n+ redis := machine.GetNativeContainer(ctx, b)\n+ if err := redis.Spawn(ctx, dockerutil.RunOpts{\n+ Image: \"benchmarks/redis\",\n+ }); err != nil {\n+ redis.CleanUp(ctx)\n+ b.Fatalf(\"failed to spwan redis instance: %v\", err)\n+ }\n+\n+ if out, err := redis.WaitForOutput(ctx, \"Ready to accept connections\", 3*time.Second); err != nil {\n+ redis.CleanUp(ctx)\n+ b.Fatalf(\"failed to start redis server: %v %s\", err, out)\n+ }\n+ redisIP, err := redis.FindIP(ctx, false)\n+ if err != nil {\n+ redis.CleanUp(ctx)\n+ b.Fatalf(\"failed to get IP from redis instance: %v\", err)\n+ }\n+ return redis, redisIP\n+}\n+\n+// runServerWorkload runs a server workload defined by 'runOpts' and 'cmd'.\n+// 'clientMachine' is used to connect to the server on 'serverMachine'.\n+func runServerWorkload(ctx context.Context, b *testing.B, args serverArgs) {\n+ b.Helper()\n+\n+ b.ResetTimer()\n+ for i := 0; i < b.N; i++ {\n+ if err := func() error {\n+ server := args.machine.GetContainer(ctx, b)\n+ defer func() {\n+ b.StopTimer()\n+ // Cleanup servers as we run so that we can go indefinitely.\n+ server.CleanUp(ctx)\n+ b.StartTimer()\n+ }()\n+ if err := server.Spawn(ctx, args.runOpts, args.cmd...); err != nil {\n+ return fmt.Errorf(\"failed to spawn node instance: %v\", err)\n+ }\n+\n+ servingIP, err := server.FindIP(ctx, false)\n+ if err != nil {\n+ return fmt.Errorf(\"failed to get ip from server: %v\", err)\n+ }\n+\n+ // Wait until the Client sees the server as up.\n+ if err := harness.WaitUntilServing(ctx, args.machine, servingIP, args.port); err != nil {\n+ return fmt.Errorf(\"failed to wait for serving: %v\", err)\n+ }\n+ return nil\n+ }(); err != nil {\n+ b.Fatal(err)\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/base/sysbench_test.go",
"new_path": "test/benchmarks/base/sysbench_test.go",
"diff": "@@ -64,7 +64,7 @@ func BenchmarkSysbench(b *testing.B) {\n},\n}\n- machine, err := h.GetMachine()\n+ machine, err := testHarness.GetMachine()\nif err != nil {\nb.Fatalf(\"failed to get machine: %v\", err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/harness/util.go",
"new_path": "test/benchmarks/harness/util.go",
"diff": "@@ -23,23 +23,25 @@ import (\n\"gvisor.dev/gvisor/pkg/test/testutil\"\n)\n+//TODO(gvisor.dev/issue/3535): move to own package or move methods to harness struct.\n+\n// WaitUntilServing grabs a container from `machine` and waits for a server at\n// IP:port.\nfunc WaitUntilServing(ctx context.Context, machine Machine, server net.IP, port int) error {\n- var logger testutil.DefaultLogger = \"netcat\"\n+ var logger testutil.DefaultLogger = \"util\"\nnetcat := machine.GetNativeContainer(ctx, logger)\ndefer netcat.CleanUp(ctx)\n- cmd := fmt.Sprintf(\"while ! nc -zv %s %d; do true; done\", server, port)\n+ cmd := fmt.Sprintf(\"while ! wget -q --spider http://%s:%d; do true; done\", server, port)\n_, err := netcat.Run(ctx, dockerutil.RunOpts{\n- Image: \"packetdrill\",\n+ Image: \"benchmarks/util\",\n}, \"sh\", \"-c\", cmd)\nreturn err\n}\n// DropCaches drops caches on the provided machine. Requires root.\nfunc DropCaches(machine Machine) error {\n- if out, err := machine.RunCommand(\"/bin/sh\", \"-c\", \"sync | sysctl vm.drop_caches=3\"); err != nil {\n+ if out, err := machine.RunCommand(\"/bin/sh\", \"-c\", \"sync && sysctl vm.drop_caches=3\"); err != nil {\nreturn fmt.Errorf(\"failed to drop caches: %v logs: %s\", err, out)\n}\nreturn nil\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/network/nginx_test.go",
"new_path": "test/benchmarks/network/nginx_test.go",
"diff": "@@ -25,7 +25,7 @@ import (\n// BenchmarkNginxConcurrency iterates the concurrency argument and tests\n// how well the runtime under test handles requests in parallel.\n-// TODO(zkoopmans): Update with different doc sizes like Httpd.\n+// TODO(gvisor.dev/issue/3536): Update with different doc sizes like Httpd.\nfunc BenchmarkNginxConcurrency(b *testing.B) {\n// Grab a machine for the client and server.\nclientMachine, err := h.GetMachine()\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/tools/BUILD",
"new_path": "test/benchmarks/tools/BUILD",
"diff": "@@ -9,6 +9,7 @@ go_library(\n\"fio.go\",\n\"hey.go\",\n\"iperf.go\",\n+ \"meminfo.go\",\n\"redis.go\",\n\"sysbench.go\",\n\"tools.go\",\n@@ -24,6 +25,7 @@ go_test(\n\"fio_test.go\",\n\"hey_test.go\",\n\"iperf_test.go\",\n+ \"meminfo_test.go\",\n\"redis_test.go\",\n\"sysbench_test.go\",\n],\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/benchmarks/tools/meminfo.go",
"diff": "+// Copyright 2020 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+// Meminfo wraps measurements of MemAvailable using /proc/meminfo.\n+type Meminfo struct {\n+}\n+\n+// MakeCmd returns a command for checking meminfo.\n+func (*Meminfo) MakeCmd() (string, []string) {\n+ return \"cat\", []string{\"/proc/meminfo\"}\n+}\n+\n+// Report takes two reads of meminfo, parses them, and reports the difference\n+// divided by b.N.\n+func (*Meminfo) Report(b *testing.B, before, after string) {\n+ b.Helper()\n+\n+ beforeVal, err := parseMemAvailable(before)\n+ if err != nil {\n+ b.Fatalf(\"could not parse before value %s: %v\", before, err)\n+ }\n+\n+ afterVal, err := parseMemAvailable(after)\n+ if err != nil {\n+ b.Fatalf(\"could not parse before value %s: %v\", before, err)\n+ }\n+ val := 1024 * ((beforeVal - afterVal) / float64(b.N))\n+ b.ReportMetric(val, \"average_container_size_bytes\")\n+}\n+\n+var memInfoRE = regexp.MustCompile(`MemAvailable:\\s*(\\d+)\\skB\\n`)\n+\n+// parseMemAvailable grabs the MemAvailable number from /proc/meminfo.\n+func parseMemAvailable(data string) (float64, error) {\n+ match := memInfoRE.FindStringSubmatch(data)\n+ if len(match) < 2 {\n+ return 0, fmt.Errorf(\"couldn't find MemAvailable in %s\", data)\n+ }\n+ return strconv.ParseFloat(match[1], 64)\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/benchmarks/tools/meminfo_test.go",
"diff": "+// Copyright 2020 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+ \"testing\"\n+)\n+\n+// TestMeminfo checks the Meminfo parser on sample output.\n+func TestMeminfo(t *testing.T) {\n+ sampleData := `\n+MemTotal: 16337408 kB\n+MemFree: 3742696 kB\n+MemAvailable: 9319948 kB\n+Buffers: 1433884 kB\n+Cached: 4607036 kB\n+SwapCached: 45284 kB\n+Active: 8288376 kB\n+Inactive: 2685928 kB\n+Active(anon): 4724912 kB\n+Inactive(anon): 1047940 kB\n+Active(file): 3563464 kB\n+Inactive(file): 1637988 kB\n+Unevictable: 326940 kB\n+Mlocked: 48 kB\n+SwapTotal: 33292284 kB\n+SwapFree: 32865736 kB\n+Dirty: 708 kB\n+Writeback: 0 kB\n+AnonPages: 4304204 kB\n+Mapped: 975424 kB\n+Shmem: 910292 kB\n+KReclaimable: 744532 kB\n+Slab: 1058448 kB\n+SReclaimable: 744532 kB\n+SUnreclaim: 313916 kB\n+KernelStack: 25188 kB\n+PageTables: 65300 kB\n+NFS_Unstable: 0 kB\n+Bounce: 0 kB\n+WritebackTmp: 0 kB\n+CommitLimit: 41460988 kB\n+Committed_AS: 22859492 kB\n+VmallocTotal: 34359738367 kB\n+VmallocUsed: 63088 kB\n+VmallocChunk: 0 kB\n+Percpu: 9248 kB\n+HardwareCorrupted: 0 kB\n+AnonHugePages: 786432 kB\n+ShmemHugePages: 0 kB\n+ShmemPmdMapped: 0 kB\n+FileHugePages: 0 kB\n+FilePmdMapped: 0 kB\n+HugePages_Total: 0\n+HugePages_Free: 0\n+HugePages_Rsvd: 0\n+HugePages_Surp: 0\n+Hugepagesize: 2048 kB\n+Hugetlb: 0 kB\n+DirectMap4k: 5408532 kB\n+DirectMap2M: 11241472 kB\n+DirectMap1G: 1048576 kB\n+`\n+ want := 9319948.0\n+ got, err := parseMemAvailable(sampleData)\n+ if err != nil {\n+ t.Fatalf(\"parseMemAvailable failed: %v\", err)\n+ }\n+ if got != want {\n+ t.Fatalf(\"parseMemAvailable got %f, want %f\", got, want)\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Port Startup and Density Benchmarks.
PiperOrigin-RevId: 325497346 |
259,975 | 07.08.2020 13:47:03 | 25,200 | 7b9bfc0ce094b0fd0cb3beec665a7b64c4ec552e | Port Ruby benchmark. | [
{
"change_type": "MODIFY",
"old_path": "images/Makefile",
"new_path": "images/Makefile",
"diff": "@@ -59,9 +59,9 @@ local_image = $(LOCAL_IMAGE_PREFIX)/$(subst _,/,$(1))\n# we need to explicitly repull the base layer in order to ensure that the\n# architecture is correct. Note that we use the term \"rebuild\" here to avoid\n# conflicting with the bazel \"build\" terminology, which is used elsewhere.\n+rebuild-%: FROM=$(shell grep FROM $(call path,$*)/Dockerfile } cut -d' ' -f2)\nrebuild-%: register-cross\n- FROM=$(shell grep FROM $(call path,$*)/Dockerfile | cut -d' ' -f2-) && \\\n- docker pull $(DOCKER_PLATFORM_ARGS) $$FROM\n+ $(foreach IMAGE,$(FROM),docker $(DOCKER_PLATFORM_ARGS) $(IMAGE); &&) true\nT=$$(mktemp -d) && cp -a $(call path,$*)/* $$T && \\\ndocker build $(DOCKER_PLATFORM_ARGS) -t $(call remote_image,$*) $$T && \\\nrm -rf $$T\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/ruby/Dockerfile",
"diff": "+# example based on https://github.com/errm/fib\n+FROM alpine:3.9 as build\n+\n+COPY Gemfile Gemfile.lock ./\n+\n+RUN apk add --no-cache ruby ruby-dev ruby-bundler ruby-json build-base bash \\\n+ && bundle install --frozen -j4 -r3 --no-cache --without development \\\n+ && apk del --no-cache ruby-bundler \\\n+ && rm -rf /usr/lib/ruby/gems/*/cache\n+\n+FROM alpine:3.9 as prod\n+\n+COPY --from=build /usr/lib/ruby/gems /usr/lib/ruby/gems\n+RUN apk add --no-cache ruby ruby-json ruby-etc redis apache2-utils \\\n+ && ruby -e \"Gem::Specification.map.each do |spec| \\\n+ Gem::Installer.for_spec( \\\n+ spec, \\\n+ wrappers: true, \\\n+ force: true, \\\n+ install_dir: spec.base_dir, \\\n+ build_args: spec.build_args, \\\n+ ).generate_bin \\\n+ end\"\n+\n+COPY . /app/.\n+\n+STOPSIGNAL SIGINT\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/ruby/Gemfile",
"diff": "+source \"https://rubygems.org\"\n+\n+gem \"sinatra\"\n+gem \"puma\"\n+gem \"redis\"\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/ruby/Gemfile.lock",
"diff": "+GEM\n+ remote: https://rubygems.org/\n+ specs:\n+ mustermann (1.0.3)\n+ puma (3.4.0)\n+ rack (2.0.6)\n+ rack-protection (2.0.5)\n+ rack\n+ redis (4.1.0)\n+ sinatra (2.0.5)\n+ mustermann (~> 1.0)\n+ rack (~> 2.0)\n+ rack-protection (= 2.0.5)\n+ tilt (~> 2.0)\n+ tilt (2.0.9)\n+\n+PLATFORMS\n+ ruby\n+\n+DEPENDENCIES\n+ puma\n+ redis\n+ sinatra\n+\n+BUNDLED WITH\n+ 1.17.1\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/ruby/config.ru",
"diff": "+require './main'\n+run Sinatra::Application\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/ruby/index.erb",
"diff": "+<!DOCTYPE html>\n+<html>\n+<body>\n+ <% text.each do |t| %>\n+ <p><%= t %></p>\n+ <% end %>\n+</body>\n+</html>\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/benchmarks/ruby/main.rb",
"diff": "+require \"sinatra\"\n+require \"securerandom\"\n+require \"redis\"\n+\n+redis_host = ENV[\"HOST\"]\n+$redis = Redis.new(host: redis_host)\n+\n+def generateText\n+ for i in 0..99\n+ $redis.set(i, randomBody(1024))\n+ end\n+end\n+\n+def randomBody(length)\n+ return SecureRandom.alphanumeric(length)\n+end\n+\n+generateText\n+template = ERB.new(File.read('./index.erb'))\n+\n+get \"/\" do\n+ texts = Array.new\n+ for i in 0..4\n+ texts.push($redis.get(rand(0..99)))\n+ end\n+ template.result_with_hash(text: texts)\n+end\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/test/dockerutil/container.go",
"new_path": "pkg/test/dockerutil/container.go",
"diff": "@@ -58,12 +58,6 @@ type Container struct {\n// a handle to restart the profile. Generally, tests/benchmarks using\n// profiles need to run as root.\nprofiles []Profile\n-\n- // Stores streams attached to the container. Used by WaitForOutputSubmatch.\n- streams types.HijackedResponse\n-\n- // stores previously read data from the attached streams.\n- streamBuf bytes.Buffer\n}\n// RunOpts are options for running a container.\n@@ -175,11 +169,25 @@ func (c *Container) SpawnProcess(ctx context.Context, r RunOpts, args ...string)\nreturn Process{}, err\n}\n+ // Open a connection to the container for parsing logs and for TTY.\n+ stream, err := c.client.ContainerAttach(ctx, c.id,\n+ types.ContainerAttachOptions{\n+ Stream: true,\n+ Stdin: true,\n+ Stdout: true,\n+ Stderr: true,\n+ })\n+ if err != nil {\n+ return Process{}, fmt.Errorf(\"connect failed container id %s: %v\", c.id, err)\n+ }\n+\n+ c.cleanups = append(c.cleanups, func() { stream.Close() })\n+\nif err := c.Start(ctx); err != nil {\nreturn Process{}, err\n}\n- return Process{container: c, conn: c.streams}, nil\n+ return Process{container: c, conn: stream}, nil\n}\n// Run is analogous to 'docker run'.\n@@ -273,23 +281,6 @@ func (c *Container) hostConfig(r RunOpts) *container.HostConfig {\n// Start is analogous to 'docker start'.\nfunc (c *Container) Start(ctx context.Context) error {\n-\n- // Open a connection to the container for parsing logs and for TTY.\n- streams, err := c.client.ContainerAttach(ctx, c.id,\n- types.ContainerAttachOptions{\n- Stream: true,\n- Stdin: true,\n- Stdout: true,\n- Stderr: true,\n- })\n- if err != nil {\n- return fmt.Errorf(\"failed to connect to container: %v\", err)\n- }\n-\n- c.streams = streams\n- c.cleanups = append(c.cleanups, func() {\n- c.streams.Close()\n- })\nif err := c.client.ContainerStart(ctx, c.id, types.ContainerStartOptions{}); err != nil {\nreturn fmt.Errorf(\"ContainerStart failed: %v\", err)\n}\n@@ -485,34 +476,19 @@ func (c *Container) WaitForOutput(ctx context.Context, pattern string, timeout t\n// WaitForOutputSubmatch searches container logs for the given\n// pattern or times out. It returns any regexp submatches as well.\nfunc (c *Container) WaitForOutputSubmatch(ctx context.Context, pattern string, timeout time.Duration) ([]string, error) {\n+ ctx, cancel := context.WithTimeout(ctx, timeout)\n+ defer cancel()\nre := regexp.MustCompile(pattern)\n- if matches := re.FindStringSubmatch(c.streamBuf.String()); matches != nil {\n- return matches, nil\n- }\n-\n- for exp := time.Now().Add(timeout); time.Now().Before(exp); {\n- select {\n- case <-ctx.Done():\n- return nil, ctx.Err()\n- default:\n- }\n-\n- c.streams.Conn.SetDeadline(time.Now().Add(50 * time.Millisecond))\n- _, err := stdcopy.StdCopy(&c.streamBuf, &c.streamBuf, c.streams.Reader)\n-\n+ for {\n+ logs, err := c.Logs(ctx)\nif err != nil {\n- // check that it wasn't a timeout\n- if nerr, ok := err.(net.Error); !ok || !nerr.Timeout() {\n- return nil, err\n- }\n+ return nil, fmt.Errorf(\"failed to get logs: %v logs: %s\", err, logs)\n}\n-\n- if matches := re.FindStringSubmatch(c.streamBuf.String()); matches != nil {\n+ if matches := re.FindStringSubmatch(logs); matches != nil {\nreturn matches, nil\n}\n+ time.Sleep(50 * time.Millisecond)\n}\n-\n- return nil, fmt.Errorf(\"timeout waiting for output %q: out: %s\", re.String(), c.streamBuf.String())\n}\n// Kill kills the container.\n@@ -537,8 +513,18 @@ func (c *Container) CleanUp(ctx context.Context) {\nfor _, profile := range c.profiles {\nprofile.OnCleanUp(c)\n}\n+\n// Forget profiles.\nc.profiles = nil\n+\n+ // Execute all cleanups. We execute cleanups here to close any\n+ // open connections to the container before closing. Open connections\n+ // can cause Kill and Remove to hang.\n+ for _, c := range c.cleanups {\n+ c()\n+ }\n+ c.cleanups = nil\n+\n// Kill the container.\nif err := c.Kill(ctx); err != nil && !strings.Contains(err.Error(), \"is not running\") {\n// Just log; can't do anything here.\n@@ -550,9 +536,4 @@ func (c *Container) CleanUp(ctx context.Context) {\n}\n// Forget all mounts.\nc.mounts = nil\n- // Execute all cleanups.\n- for _, c := range c.cleanups {\n- c()\n- }\n- c.cleanups = nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/network/BUILD",
"new_path": "test/benchmarks/network/BUILD",
"diff": "@@ -17,6 +17,7 @@ go_test(\n\"iperf_test.go\",\n\"nginx_test.go\",\n\"node_test.go\",\n+ \"ruby_test.go\",\n],\nlibrary = \":network\",\ntags = [\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/network/node_test.go",
"new_path": "test/benchmarks/network/node_test.go",
"diff": "@@ -24,18 +24,16 @@ import (\n\"gvisor.dev/gvisor/test/benchmarks/tools\"\n)\n-// BenchmarkNode runs 10K requests using 'hey' against a Node server run on\n+// BenchmarkNode runs requests using 'hey' against a Node server run on\n// 'runtime'. The server responds to requests by grabbing some data in a\n// redis instance and returns the data in its reponse. The test loops through\n// increasing amounts of concurency for requests.\nfunc BenchmarkNode(b *testing.B) {\n- requests := 10000\nconcurrency := []int{1, 5, 10, 25}\n-\nfor _, c := range concurrency {\nb.Run(fmt.Sprintf(\"Concurrency%d\", c), func(b *testing.B) {\nhey := &tools.Hey{\n- Requests: requests,\n+ Requests: b.N * c, // Requests b.N requests per thread.\nConcurrency: c,\n}\nrunNode(b, hey)\n@@ -113,7 +111,6 @@ func runNode(b *testing.B, hey *tools.Hey) {\nnodeApp.RestartProfiles()\nb.ResetTimer()\n- for i := 0; i < b.N; i++ {\n// the client should run on Native.\nclient := clientMachine.GetNativeContainer(ctx, b)\nout, err := client.Run(ctx, dockerutil.RunOpts{\n@@ -128,4 +125,3 @@ func runNode(b *testing.B, hey *tools.Hey) {\nhey.Report(b, out)\nb.StartTimer()\n}\n-}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/benchmarks/network/ruby_test.go",
"diff": "+// Copyright 2020 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+package network\n+\n+import (\n+ \"context\"\n+ \"fmt\"\n+ \"testing\"\n+ \"time\"\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+// BenchmarkRuby runs requests using 'hey' against a ruby application server.\n+// On start, ruby app generates some random data and pushes it to a redis\n+// instance. On a request, the app grabs for random entries from the redis\n+// server, publishes it to a document, and returns the doc to the request.\n+func BenchmarkRuby(b *testing.B) {\n+ concurrency := []int{1, 5, 10, 25}\n+ for _, c := range concurrency {\n+ b.Run(fmt.Sprintf(\"Concurrency%d\", c), func(b *testing.B) {\n+ hey := &tools.Hey{\n+ Requests: b.N * c, // b.N requests per thread.\n+ Concurrency: c,\n+ }\n+ runRuby(b, hey)\n+ })\n+ }\n+}\n+\n+// runRuby runs the test for a given # of requests and concurrency.\n+func runRuby(b *testing.B, hey *tools.Hey) {\n+ b.Helper()\n+ // The machine to hold Redis and the Ruby Server.\n+ serverMachine, err := h.GetMachine()\n+ if err != nil {\n+ b.Fatal(\"failed to get machine with: %v\", err)\n+ }\n+ defer serverMachine.CleanUp()\n+\n+ // The machine to run 'hey'.\n+ clientMachine, err := h.GetMachine()\n+ if err != nil {\n+ b.Fatal(\"failed to get machine with: %v\", err)\n+ }\n+ defer clientMachine.CleanUp()\n+ ctx := context.Background()\n+\n+ // Spawn a redis instance for the app to use.\n+ redis := serverMachine.GetNativeContainer(ctx, b)\n+ if err := redis.Spawn(ctx, dockerutil.RunOpts{\n+ Image: \"benchmarks/redis\",\n+ }); err != nil {\n+ b.Fatalf(\"failed to spwan redis instance: %v\", err)\n+ }\n+ defer redis.CleanUp(ctx)\n+\n+ if out, err := redis.WaitForOutput(ctx, \"Ready to accept connections\", 3*time.Second); err != nil {\n+ b.Fatalf(\"failed to start redis server: %v %s\", err, out)\n+ }\n+ redisIP, err := redis.FindIP(ctx, false)\n+ if err != nil {\n+ b.Fatalf(\"failed to get IP from redis instance: %v\", err)\n+ }\n+\n+ // Ruby runs on port 9292.\n+ const port = 9292\n+\n+ // Start-up the Ruby server.\n+ rubyApp := serverMachine.GetContainer(ctx, b)\n+ if err := rubyApp.Spawn(ctx, dockerutil.RunOpts{\n+ Image: \"benchmarks/ruby\",\n+ WorkDir: \"/app\",\n+ Links: []string{redis.MakeLink(\"redis\")},\n+ Ports: []int{port},\n+ Env: []string{\n+ fmt.Sprintf(\"PORT=%d\", port),\n+ \"WEB_CONCURRENCY=20\",\n+ \"WEB_MAX_THREADS=20\",\n+ \"RACK_ENV=production\",\n+ fmt.Sprintf(\"HOST=%s\", redisIP),\n+ },\n+ User: \"nobody\",\n+ }, \"sh\", \"-c\", \"/usr/bin/puma\"); err != nil {\n+ b.Fatalf(\"failed to spawn node instance: %v\", err)\n+ }\n+ defer rubyApp.CleanUp(ctx)\n+\n+ servingIP, err := serverMachine.IPAddress()\n+ if err != nil {\n+ b.Fatalf(\"failed to get ip from server: %v\", err)\n+ }\n+\n+ servingPort, err := rubyApp.FindPort(ctx, port)\n+ if err != nil {\n+ b.Fatalf(\"failed to port from node instance: %v\", err)\n+ }\n+\n+ // Wait until the Client sees the server as up.\n+ if err := harness.WaitUntilServing(ctx, clientMachine, servingIP, servingPort); err != nil {\n+ b.Fatalf(\"failed to wait until serving: %v\", err)\n+ }\n+ heyCmd := hey.MakeCmd(servingIP, servingPort)\n+ rubyApp.RestartProfiles()\n+ b.ResetTimer()\n+\n+ // the client should run on Native.\n+ client := clientMachine.GetNativeContainer(ctx, b)\n+ defer client.CleanUp(ctx)\n+ out, err := client.Run(ctx, dockerutil.RunOpts{\n+ Image: \"benchmarks/hey\",\n+ }, heyCmd...)\n+ if err != nil {\n+ b.Fatalf(\"hey container failed: %v logs: %s\", err, out)\n+ }\n+\n+ // Stop the timer to parse the data and report stats.\n+ b.StopTimer()\n+ hey.Report(b, out)\n+ b.StartTimer()\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/tools/hey.go",
"new_path": "test/benchmarks/tools/hey.go",
"diff": "@@ -25,7 +25,7 @@ import (\n// Hey is for the client application 'hey'.\ntype Hey struct {\n- Requests int\n+ Requests int // Note: requests cannot be less than concurrency.\nConcurrency int\nDoc string\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Port Ruby benchmark.
PiperOrigin-RevId: 325500772 |
259,885 | 07.08.2020 16:33:37 | 25,200 | 0b7cd1e751f70cf6b335754d2b173d9c12b674c7 | Mark dropped pages unevictable in fsimpl/gofer.dentry.destroyLocked. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -1264,8 +1264,11 @@ func (d *dentry) destroyLocked(ctx context.Context) {\n}\n}\n// Discard cached data.\n+ if !d.cache.IsEmpty() {\n+ mf.MarkAllUnevictable(d)\nd.cache.DropAll(mf)\nd.dirty.RemoveAll()\n+ }\nd.dataMu.Unlock()\n// Clunk open fids and close open host FDs.\nif !d.readFile.isNil() {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Mark dropped pages unevictable in fsimpl/gofer.dentry.destroyLocked.
PiperOrigin-RevId: 325531657 |
259,853 | 07.08.2020 17:59:07 | 25,200 | b7a97fe33541fa400cc2b949baf0b31634d2410c | Remove doc rules for non-existent files
These files have been deleted by cl/324775563. | [
{
"change_type": "MODIFY",
"old_path": "shim/v1/BUILD",
"new_path": "shim/v1/BUILD",
"diff": "load(\"//tools:defs.bzl\", \"go_binary\")\n-load(\"//website:defs.bzl\", \"doc\")\npackage(licenses = [\"notice\"])\n@@ -29,13 +28,3 @@ go_binary(\n\"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n-\n-doc(\n- name = \"doc\",\n- src = \"README.md\",\n- category = \"User Guide\",\n- permalink = \"/docs/user_guide/gvisor-containerd-shim/\",\n- subcategory = \"Advanced\",\n- visibility = [\"//website:__pkg__\"],\n- weight = \"93\",\n-)\n"
},
{
"change_type": "MODIFY",
"old_path": "shim/v2/BUILD",
"new_path": "shim/v2/BUILD",
"diff": "load(\"//tools:defs.bzl\", \"go_binary\")\n-load(\"//website:defs.bzl\", \"doc\")\npackage(licenses = [\"notice\"])\n@@ -17,13 +16,3 @@ go_binary(\n\"@com_github_containerd_containerd//runtime/v2/shim:go_default_library\",\n],\n)\n-\n-doc(\n- name = \"doc\",\n- src = \"README.md\",\n- category = \"User Guide\",\n- permalink = \"/docs/user_guide/containerd-shim-runsc-v1/\",\n- subcategory = \"Advanced\",\n- visibility = [\"//website:__pkg__\"],\n- weight = \"92\",\n-)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove doc rules for non-existent files
These files have been deleted by cl/324775563.
PiperOrigin-RevId: 325543067 |
259,885 | 07.08.2020 18:32:03 | 25,200 | 343661770aa96efe3b539a82addff13df235413f | Don't hold gofer.filesystem.renameMu during dentry destruction. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -1158,7 +1158,8 @@ func (d *dentry) OnZeroWatches(ctx context.Context) {\n// operation. One of the calls may destroy the dentry, so subsequent calls will\n// do nothing.\n//\n-// Preconditions: d.fs.renameMu must be locked for writing.\n+// Preconditions: d.fs.renameMu must be locked for writing; it may be\n+// temporarily unlocked.\nfunc (d *dentry) checkCachingLocked(ctx context.Context) {\n// Dentries with a non-zero reference count must be retained. (The only way\n// to obtain a reference on a dentry with zero references is via path\n@@ -1238,11 +1239,13 @@ func (d *dentry) checkCachingLocked(ctx context.Context) {\n}\n}\n-// destroyLocked destroys the dentry. It may flushes dirty pages from cache,\n-// close p9 file and remove reference on parent dentry.\n+// destroyLocked destroys the dentry.\n//\n-// Preconditions: d.fs.renameMu must be locked for writing. d.refs == 0. d is\n-// not a child dentry.\n+// Preconditions:\n+// * d.fs.renameMu must be locked for writing; it may be temporarily unlocked.\n+// * d.refs == 0.\n+// * d.parent.children[d.name] != d, i.e. d is not reachable by path traversal\n+// from its former parent dentry.\nfunc (d *dentry) destroyLocked(ctx context.Context) {\nswitch atomic.LoadInt64(&d.refs) {\ncase 0:\n@@ -1254,6 +1257,10 @@ func (d *dentry) destroyLocked(ctx context.Context) {\npanic(\"dentry.destroyLocked() called with references on the dentry\")\n}\n+ // Allow the following to proceed without renameMu locked to improve\n+ // scalability.\n+ d.fs.renameMu.Unlock()\n+\nmf := d.fs.mfp.MemoryFile()\nd.handleMu.Lock()\nd.dataMu.Lock()\n@@ -1315,6 +1322,9 @@ func (d *dentry) destroyLocked(ctx context.Context) {\ndelete(d.fs.syncableDentries, d)\nd.fs.syncMu.Unlock()\n}\n+\n+ d.fs.renameMu.Lock()\n+\n// Drop the reference held by d on its parent without recursively locking\n// d.fs.renameMu.\nif d.parent != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer_test.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer_test.go",
"diff": "@@ -52,6 +52,8 @@ func TestDestroyIdempotent(t *testing.T) {\n}\nparent.cacheNewChildLocked(child, \"child\")\n+ fs.renameMu.Lock()\n+ defer fs.renameMu.Unlock()\nchild.checkCachingLocked(ctx)\nif got := atomic.LoadInt64(&child.refs); got != -1 {\nt.Fatalf(\"child.refs=%d, want: -1\", got)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't hold gofer.filesystem.renameMu during dentry destruction.
PiperOrigin-RevId: 325546629 |
259,853 | 07.08.2020 22:47:55 | 25,200 | 13a8ae81b2361cd32f8e73d14ca5b9bca9569b1a | Add context.FullStateChanged()
It indicates that the Sentry has changed the state of the thread and
next calls of PullFullState() has to do nothing. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/ptrace.go",
"new_path": "pkg/sentry/kernel/ptrace.go",
"diff": "@@ -1063,7 +1063,7 @@ func (t *Task) Ptrace(req int64, pid ThreadID, addr, data usermem.Addr) error {\nif err != nil {\nreturn err\n}\n- t.p.FloatingPointStateChanged()\n+ t.p.FullStateChanged()\nar.End -= usermem.Addr(n)\nreturn t.CopyOutIovecs(data, usermem.AddrRangeSeqOf(ar))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_exec.go",
"new_path": "pkg/sentry/kernel/task_exec.go",
"diff": "@@ -226,6 +226,7 @@ func (r *runSyscallAfterExecStop) execute(t *Task) taskRunState {\nt.tc = *r.tc\nt.mu.Unlock()\nt.unstopVforkParent()\n+ t.p.FullStateChanged()\n// NOTE(b/30316266): All locks must be dropped prior to calling Activate.\nt.MemoryManager().Activate(t)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_signals.go",
"new_path": "pkg/sentry/kernel/task_signals.go",
"diff": "@@ -280,7 +280,7 @@ func (t *Task) deliverSignalToHandler(info *arch.SignalInfo, act arch.SignalAct)\nif err := t.Arch().SignalSetup(st, &act, info, &alt, mask); err != nil {\nreturn err\n}\n- t.p.FloatingPointStateChanged()\n+ t.p.FullStateChanged()\nt.haveSavedSignalMask = false\n// Add our signal mask.\n@@ -312,7 +312,7 @@ func (t *Task) SignalReturn(rt bool) (*SyscallControl, error) {\n// Restore our signal mask. SIGKILL and SIGSTOP should not be blocked.\nt.SetSignalMask(sigset &^ UnblockableSignals)\n- t.p.FloatingPointStateChanged()\n+ t.p.FullStateChanged()\nreturn ctrlResume, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/context.go",
"new_path": "pkg/sentry/platform/kvm/context.go",
"diff": "@@ -91,8 +91,8 @@ func (c *context) Interrupt() {\n// Release implements platform.Context.Release().\nfunc (c *context) Release() {}\n-// FloatingPointStateChanged implements platform.Context.FloatingPointStateChanged.\n-func (c *context) FloatingPointStateChanged() {}\n+// FullStateChanged implements platform.Context.FullStateChanged.\n+func (c *context) FullStateChanged() {}\n// PullFullState implements platform.Context.PullFullState.\nfunc (c *context) PullFullState(as platform.AddressSpace, ac arch.Context) {}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/platform.go",
"new_path": "pkg/sentry/platform/platform.go",
"diff": "@@ -171,14 +171,20 @@ type Context interface {\n// Preconditions: The caller must be running on the task goroutine.\nPullFullState(as AddressSpace, ac arch.Context)\n- // FloatingPointStateChanged forces restoring a full state of the application thread.\n+ // FullStateChanged() indicates that a thread state has been changed by\n+ // the Sentry. This happens in case of the rt_sigreturn, execve, etc.\n//\n- // A platform can support lazy loading/restoring of a thread state.\n- // This means that if the Sentry has not changed a thread state,\n+ // First, it indicates that the Sentry has the full state of the thread\n+ // and PullFullState() has to do nothing if it is called after\n+ // FullStateChanged().\n+ //\n+ // Second, it forces restoring the full state of the application\n+ // thread. A platform can support lazy loading/restoring of a thread\n+ // state. This means that if the Sentry has not changed a thread state,\n// the platform may not restore it.\n//\n// Preconditions: The caller must be running on the task goroutine.\n- FloatingPointStateChanged()\n+ FullStateChanged()\n// Interrupt interrupts a concurrent call to Switch(), causing it to return\n// ErrContextInterrupt.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/ptrace.go",
"new_path": "pkg/sentry/platform/ptrace/ptrace.go",
"diff": "@@ -182,8 +182,8 @@ func (c *context) Interrupt() {\n// Release implements platform.Context.Release().\nfunc (c *context) Release() {}\n-// FloatingPointStateChanged implements platform.Context.FloatingPointStateChanged.\n-func (c *context) FloatingPointStateChanged() {}\n+// FullStateChanged implements platform.Context.FullStateChanged.\n+func (c *context) FullStateChanged() {}\n// PullFullState implements platform.Context.PullFullState.\nfunc (c *context) PullFullState(as platform.AddressSpace, ac arch.Context) {}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add context.FullStateChanged()
It indicates that the Sentry has changed the state of the thread and
next calls of PullFullState() has to do nothing.
PiperOrigin-RevId: 325567415 |
260,004 | 08.08.2020 17:43:15 | 25,200 | b404b5c255214a37d7f787f9fe24bb8e22509eb4 | Use unicast source for ICMP echo replies
Packets MUST NOT use a non-unicast source address for ICMP
Echo Replies.
Test: integration_test.TestPingMulticastBroadcast | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/icmp.go",
"new_path": "pkg/tcpip/network/ipv4/icmp.go",
"diff": "@@ -96,6 +96,26 @@ func (e *endpoint) handleICMP(r *stack.Route, pkt *stack.PacketBuffer) {\nNetworkHeader: append(buffer.View(nil), pkt.NetworkHeader...),\n})\n+ remoteLinkAddr := r.RemoteLinkAddress\n+\n+ // As per RFC 1122 section 3.2.1.3, when a host sends any datagram, the IP\n+ // source address MUST be one of its own IP addresses (but not a broadcast\n+ // or multicast address).\n+ localAddr := r.LocalAddress\n+ if r.IsInboundBroadcast() || header.IsV4MulticastAddress(r.LocalAddress) {\n+ localAddr = \"\"\n+ }\n+\n+ r, err := r.Stack().FindRoute(e.NICID(), localAddr, r.RemoteAddress, ProtocolNumber, false /* multicastLoop */)\n+ if err != nil {\n+ // If we cannot find a route to the destination, silently drop the packet.\n+ return\n+ }\n+ defer r.Release()\n+\n+ // Use the remote link address from the incoming packet.\n+ r.ResolveWith(remoteLinkAddr)\n+\nvv := pkt.Data.Clone(nil)\nvv.TrimFront(header.ICMPv4MinimumSize)\nhdr := buffer.NewPrependable(int(r.MaxHeaderLength()) + header.ICMPv4MinimumSize)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/icmp.go",
"new_path": "pkg/tcpip/network/ipv6/icmp.go",
"diff": "@@ -389,6 +389,26 @@ func (e *endpoint) handleICMP(r *stack.Route, pkt *stack.PacketBuffer, hasFragme\nreceived.Invalid.Increment()\nreturn\n}\n+\n+ remoteLinkAddr := r.RemoteLinkAddress\n+\n+ // As per RFC 4291 section 2.7, multicast addresses must not be used as\n+ // source addresses in IPv6 packets.\n+ localAddr := r.LocalAddress\n+ if header.IsV6MulticastAddress(r.LocalAddress) {\n+ localAddr = \"\"\n+ }\n+\n+ r, err := r.Stack().FindRoute(e.NICID(), localAddr, r.RemoteAddress, ProtocolNumber, false /* multicastLoop */)\n+ if err != nil {\n+ // If we cannot find a route to the destination, silently drop the packet.\n+ return\n+ }\n+ defer r.Release()\n+\n+ // Use the link address from the source of the original packet.\n+ r.ResolveWith(remoteLinkAddr)\n+\npkt.Data.TrimFront(header.ICMPv6EchoMinimumSize)\nhdr := buffer.NewPrependable(int(r.MaxHeaderLength()) + header.ICMPv6EchoMinimumSize)\npacket := header.ICMPv6(hdr.Prepend(header.ICMPv6EchoMinimumSize))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/BUILD",
"new_path": "pkg/tcpip/stack/BUILD",
"diff": "@@ -121,6 +121,7 @@ go_test(\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/link/channel\",\n\"//pkg/tcpip/link/loopback\",\n+ \"//pkg/tcpip/network/arp\",\n\"//pkg/tcpip/network/ipv4\",\n\"//pkg/tcpip/network/ipv6\",\n\"//pkg/tcpip/ports\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/route.go",
"new_path": "pkg/tcpip/stack/route.go",
"diff": "@@ -110,6 +110,12 @@ func (r *Route) GSOMaxSize() uint32 {\nreturn 0\n}\n+// ResolveWith immediately resolves a route with the specified remote link\n+// address.\n+func (r *Route) ResolveWith(addr tcpip.LinkAddress) {\n+ r.RemoteLinkAddress = addr\n+}\n+\n// Resolve attempts to resolve the link address if necessary. Returns ErrWouldBlock in\n// case address resolution requires blocking, e.g. wait for ARP reply. Waker is\n// notified when address resolution is complete (success or not).\n@@ -279,12 +285,26 @@ func (r *Route) Stack() *Stack {\nreturn r.ref.stack()\n}\n-// IsBroadcast returns true if the route is to send a broadcast packet.\n-func (r *Route) IsBroadcast() bool {\n+// IsOutboundBroadcast returns true if the route is for an outbound broadcast\n+// packet.\n+func (r *Route) IsOutboundBroadcast() bool {\n// Only IPv4 has a notion of broadcast.\nreturn r.directedBroadcast || r.RemoteAddress == header.IPv4Broadcast\n}\n+// IsInboundBroadcast returns true if the route is for an inbound broadcast\n+// packet.\n+func (r *Route) IsInboundBroadcast() bool {\n+ // Only IPv4 has a notion of broadcast.\n+ if r.LocalAddress == header.IPv4Broadcast {\n+ return true\n+ }\n+\n+ addr := r.ref.addrWithPrefix()\n+ subnet := addr.Subnet()\n+ return subnet.IsBroadcast(r.LocalAddress)\n+}\n+\n// ReverseRoute returns new route with given source and destination address.\nfunc (r *Route) ReverseRoute(src tcpip.Address, dst tcpip.Address) Route {\nreturn Route{\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -21,6 +21,7 @@ import (\n\"bytes\"\n\"fmt\"\n\"math\"\n+ \"net\"\n\"sort\"\n\"strings\"\n\"testing\"\n@@ -34,6 +35,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/channel\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/loopback\"\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@@ -3694,3 +3696,49 @@ func TestOutgoingSubnetBroadcast(t *testing.T) {\n})\n}\n}\n+\n+func TestResolveWith(t *testing.T) {\n+ const (\n+ unspecifiedNICID = 0\n+ nicID = 1\n+ )\n+\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{ipv4.NewProtocol(), arp.NewProtocol()},\n+ })\n+ ep := channel.New(0, defaultMTU, \"\")\n+ ep.LinkEPCapabilities |= stack.CapabilityResolutionRequired\n+ if err := s.CreateNIC(nicID, ep); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID, err)\n+ }\n+ addr := tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: tcpip.AddressWithPrefix{\n+ Address: tcpip.Address(net.ParseIP(\"192.168.1.58\").To4()),\n+ PrefixLen: 24,\n+ },\n+ }\n+ if err := s.AddProtocolAddress(nicID, addr); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %+v): %s\", nicID, addr, err)\n+ }\n+\n+ s.SetRouteTable([]tcpip.Route{{Destination: header.IPv4EmptySubnet, NIC: nicID}})\n+\n+ remoteAddr := tcpip.Address(net.ParseIP(\"192.168.1.59\").To4())\n+ r, err := s.FindRoute(unspecifiedNICID, \"\" /* localAddr */, remoteAddr, header.IPv4ProtocolNumber, false /* multicastLoop */)\n+ if err != nil {\n+ t.Fatalf(\"FindRoute(%d, '', %s, %d): %s\", unspecifiedNICID, remoteAddr, header.IPv4ProtocolNumber, err)\n+ }\n+ defer r.Release()\n+\n+ // Should initially require resolution.\n+ if !r.IsResolutionRequired() {\n+ t.Fatal(\"got r.IsResolutionRequired() = false, want = true\")\n+ }\n+\n+ // Manually resolving the route should no longer require resolution.\n+ r.ResolveWith(\"\\x01\")\n+ if r.IsResolutionRequired() {\n+ t.Fatal(\"got r.IsResolutionRequired() = true, want = false\")\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/BUILD",
"new_path": "pkg/tcpip/tests/integration/BUILD",
"diff": "@@ -14,6 +14,7 @@ go_test(\n\"//pkg/tcpip/network/ipv4\",\n\"//pkg/tcpip/network/ipv6\",\n\"//pkg/tcpip/stack\",\n+ \"//pkg/tcpip/transport/icmp\",\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": "package integration_test\nimport (\n+ \"net\"\n\"testing\"\n\"github.com/google/go-cmp/cmp\"\n@@ -25,43 +26,206 @@ import (\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/udp\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n-const defaultMTU = 1280\n-\n-// TestIncomingMulticastAndBroadcast tests receiving a packet destined to some\n-// multicast or broadcast address.\n-func TestIncomingMulticastAndBroadcast(t *testing.T) {\nconst (\n- nicID = 1\n- remotePort = 5555\n- localPort = 80\n+ defaultMTU = 1280\nttl = 255\n)\n- data := []byte{1, 2, 3, 4}\n-\n- // Local IPv4 subnet: 192.168.1.58/24\n- ipv4Addr := tcpip.AddressWithPrefix{\n- Address: \"\\xc0\\xa8\\x01\\x3a\",\n+var (\n+ ipv4Addr = tcpip.AddressWithPrefix{\n+ Address: tcpip.Address(net.ParseIP(\"192.168.1.58\").To4()),\nPrefixLen: 24,\n}\n- ipv4Subnet := ipv4Addr.Subnet()\n- ipv4SubnetBcast := ipv4Subnet.Broadcast()\n+ ipv4Subnet = ipv4Addr.Subnet()\n+ ipv4SubnetBcast = ipv4Subnet.Broadcast()\n- // Local IPv6 subnet: 200a::1/64\n- ipv6Addr := tcpip.AddressWithPrefix{\n- Address: \"\\x20\\x0a\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\",\n+ ipv6Addr = tcpip.AddressWithPrefix{\n+ Address: tcpip.Address(net.ParseIP(\"200a::1\").To16()),\nPrefixLen: 64,\n}\n- ipv6Subnet := ipv6Addr.Subnet()\n- ipv6SubnetBcast := ipv6Subnet.Broadcast()\n+ ipv6Subnet = ipv6Addr.Subnet()\n+ ipv6SubnetBcast = ipv6Subnet.Broadcast()\n// Remote addrs.\n- remoteIPv4Addr := tcpip.Address(\"\\x64\\x0a\\x7b\\x18\")\n- remoteIPv6Addr := tcpip.Address(\"\\x20\\x0b\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\")\n+ remoteIPv4Addr = tcpip.Address(net.ParseIP(\"10.0.0.1\").To4())\n+ remoteIPv6Addr = tcpip.Address(net.ParseIP(\"200b::1\").To16())\n+)\n+\n+// TestPingMulticastBroadcast tests that responding to an Echo Request destined\n+// to a multicast or broadcast address uses a unicast source address for the\n+// reply.\n+func TestPingMulticastBroadcast(t *testing.T) {\n+ const nicID = 1\n+\n+ rxIPv4ICMP := func(e *channel.Endpoint, dst tcpip.Address) {\n+ totalLen := header.IPv4MinimumSize + header.ICMPv4MinimumSize\n+ hdr := buffer.NewPrependable(totalLen)\n+ pkt := header.ICMPv4(hdr.Prepend(header.ICMPv4MinimumSize))\n+ pkt.SetType(header.ICMPv4Echo)\n+ pkt.SetCode(0)\n+ pkt.SetChecksum(0)\n+ pkt.SetChecksum(^header.Checksum(pkt, 0))\n+ ip := header.IPv4(hdr.Prepend(header.IPv4MinimumSize))\n+ ip.Encode(&header.IPv4Fields{\n+ IHL: header.IPv4MinimumSize,\n+ TotalLength: uint16(totalLen),\n+ Protocol: uint8(icmp.ProtocolNumber4),\n+ TTL: ttl,\n+ SrcAddr: remoteIPv4Addr,\n+ DstAddr: dst,\n+ })\n+\n+ e.InjectInbound(header.IPv4ProtocolNumber, &stack.PacketBuffer{\n+ Data: hdr.View().ToVectorisedView(),\n+ })\n+ }\n+\n+ rxIPv6ICMP := func(e *channel.Endpoint, dst tcpip.Address) {\n+ totalLen := header.IPv6MinimumSize + header.ICMPv6MinimumSize\n+ hdr := buffer.NewPrependable(totalLen)\n+ pkt := header.ICMPv6(hdr.Prepend(header.ICMPv6MinimumSize))\n+ pkt.SetType(header.ICMPv6EchoRequest)\n+ pkt.SetCode(0)\n+ pkt.SetChecksum(0)\n+ pkt.SetChecksum(header.ICMPv6Checksum(pkt, remoteIPv6Addr, dst, buffer.VectorisedView{}))\n+ ip := header.IPv6(hdr.Prepend(header.IPv6MinimumSize))\n+ ip.Encode(&header.IPv6Fields{\n+ PayloadLength: header.ICMPv6MinimumSize,\n+ NextHeader: uint8(icmp.ProtocolNumber6),\n+ HopLimit: ttl,\n+ SrcAddr: remoteIPv6Addr,\n+ DstAddr: dst,\n+ })\n+\n+ e.InjectInbound(header.IPv6ProtocolNumber, &stack.PacketBuffer{\n+ Data: hdr.View().ToVectorisedView(),\n+ })\n+ }\n+\n+ tests := []struct {\n+ name string\n+ dstAddr tcpip.Address\n+ }{\n+ {\n+ name: \"IPv4 unicast\",\n+ dstAddr: ipv4Addr.Address,\n+ },\n+ {\n+ name: \"IPv4 directed broadcast\",\n+ dstAddr: ipv4SubnetBcast,\n+ },\n+ {\n+ name: \"IPv4 broadcast\",\n+ dstAddr: header.IPv4Broadcast,\n+ },\n+ {\n+ name: \"IPv4 all-systems multicast\",\n+ dstAddr: header.IPv4AllSystems,\n+ },\n+ {\n+ name: \"IPv6 unicast\",\n+ dstAddr: ipv6Addr.Address,\n+ },\n+ {\n+ name: \"IPv6 all-nodes multicast\",\n+ dstAddr: header.IPv6AllNodesMulticastAddress,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ ipv4Proto := ipv4.NewProtocol()\n+ ipv6Proto := ipv6.NewProtocol()\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{ipv4Proto, ipv6Proto},\n+ TransportProtocols: []stack.TransportProtocol{icmp.NewProtocol4(), icmp.NewProtocol6()},\n+ })\n+ // We only expect a single packet in response to our ICMP Echo Request.\n+ e := channel.New(1, defaultMTU, \"\")\n+ if err := s.CreateNIC(nicID, e); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID, err)\n+ }\n+ ipv4ProtoAddr := tcpip.ProtocolAddress{Protocol: header.IPv4ProtocolNumber, AddressWithPrefix: ipv4Addr}\n+ if err := s.AddProtocolAddress(nicID, ipv4ProtoAddr); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %+v): %s\", nicID, ipv4ProtoAddr, err)\n+ }\n+ ipv6ProtoAddr := tcpip.ProtocolAddress{Protocol: header.IPv6ProtocolNumber, AddressWithPrefix: ipv6Addr}\n+ if err := s.AddProtocolAddress(nicID, ipv6ProtoAddr); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %+v): %s\", nicID, ipv6ProtoAddr, err)\n+ }\n+\n+ // Default routes for IPv4 and IPv6 so ICMP can find a route to the remote\n+ // node when attempting to send the ICMP Echo Reply.\n+ s.SetRouteTable([]tcpip.Route{\n+ tcpip.Route{\n+ Destination: header.IPv6EmptySubnet,\n+ NIC: nicID,\n+ },\n+ tcpip.Route{\n+ Destination: header.IPv4EmptySubnet,\n+ NIC: nicID,\n+ },\n+ })\n+\n+ var rxICMP func(*channel.Endpoint, tcpip.Address)\n+ var expectedSrc tcpip.Address\n+ var expectedDst tcpip.Address\n+ var proto stack.NetworkProtocol\n+ switch l := len(test.dstAddr); l {\n+ case header.IPv4AddressSize:\n+ rxICMP = rxIPv4ICMP\n+ expectedSrc = ipv4Addr.Address\n+ expectedDst = remoteIPv4Addr\n+ proto = ipv4Proto\n+ case header.IPv6AddressSize:\n+ rxICMP = rxIPv6ICMP\n+ expectedSrc = ipv6Addr.Address\n+ expectedDst = remoteIPv6Addr\n+ proto = ipv6Proto\n+ default:\n+ t.Fatalf(\"got unexpected address length = %d bytes\", l)\n+ }\n+\n+ rxICMP(e, test.dstAddr)\n+ pkt, ok := e.Read()\n+ if !ok {\n+ t.Fatal(\"expected ICMP response\")\n+ }\n+\n+ if pkt.Route.LocalAddress != expectedSrc {\n+ t.Errorf(\"got pkt.Route.LocalAddress = %s, want = %s\", pkt.Route.LocalAddress, expectedSrc)\n+ }\n+ if pkt.Route.RemoteAddress != expectedDst {\n+ t.Errorf(\"got pkt.Route.RemoteAddress = %s, want = %s\", pkt.Route.RemoteAddress, expectedDst)\n+ }\n+\n+ src, dst := proto.ParseAddresses(pkt.Pkt.NetworkHeader)\n+ if src != expectedSrc {\n+ t.Errorf(\"got pkt source = %s, want = %s\", src, expectedSrc)\n+ }\n+ if dst != expectedDst {\n+ t.Errorf(\"got pkt destination = %s, want = %s\", dst, expectedDst)\n+ }\n+ })\n+ }\n+\n+}\n+\n+// TestIncomingMulticastAndBroadcast tests receiving a packet destined to some\n+// multicast or broadcast address.\n+func TestIncomingMulticastAndBroadcast(t *testing.T) {\n+ const (\n+ nicID = 1\n+ remotePort = 5555\n+ localPort = 80\n+ )\n+\n+ data := []byte{1, 2, 3, 4}\nrxIPv4UDP := func(e *channel.Endpoint, dst tcpip.Address) {\npayloadLen := header.UDPMinimumSize + len(data)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -499,7 +499,7 @@ func (e *endpoint) write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, <-c\nresolve = route.Resolve\n}\n- if !e.broadcast && route.IsBroadcast() {\n+ if !e.broadcast && route.IsOutboundBroadcast() {\nreturn 0, nil, tcpip.ErrBroadcastDisabled\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use unicast source for ICMP echo replies
Packets MUST NOT use a non-unicast source address for ICMP
Echo Replies.
Test: integration_test.TestPingMulticastBroadcast
PiperOrigin-RevId: 325634380 |
259,975 | 10.08.2020 12:25:48 | 25,200 | 9ac71dc78fd1a2487780686332e54c21a1cb2cd3 | Mark DirCreation/tmp tests as passing. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -166,8 +166,9 @@ do-tests: runsc\nsimple-tests: unit-tests # Compatibility target.\n.PHONY: simple-tests\n+# Keep these in sync with //scripts/docker_tests.sh.\nIMAGE_FILTER := HelloWorld\\|Httpd\\|Ruby\\|Stdio\n-INTEGRATION_FILTER := Life\\|Pause\\|Connect\\|JobControl\\|Overlay\\|Exec\\|DirCreation/root\n+INTEGRATION_FILTER := Life\\|Pause\\|Connect\\|JobControl\\|Overlay\\|Exec\\|DirCreation\\|Link\ndocker-tests: load-basic-images\n@$(call submake,install-test-runtime RUNTIME=\"vfs1\")\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/docker_tests.sh",
"new_path": "scripts/docker_tests.sh",
"diff": "@@ -22,6 +22,7 @@ install_runsc_for_test docker\ntest_runsc //test/image:image_test //test/e2e:integration_test\ninstall_runsc_for_test docker --vfs2\n+# Sync with //Makefile.\nIMAGE_FILTER=\"Hello|Httpd|Ruby|Stdio\"\n-INTEGRATION_FILTER=\"LifeCycle|Pause|Connect|JobControl|Overlay|Exec|DirCreation/root|Link\"\n+INTEGRATION_FILTER=\"LifeCycle|Pause|Connect|JobControl|Overlay|Exec|DirCreation|Link\"\ntest_runsc //test/e2e:integration_test //test/image:image_test --test_filter=\"${IMAGE_FILTER}|${INTEGRATION_FILTER}\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Mark DirCreation/tmp tests as passing.
PiperOrigin-RevId: 325861904 |
259,891 | 10.08.2020 13:49:51 | 25,200 | 7ba5e3558aace529f9a0553015cc5074705e7a79 | ip6tables: move target-specific code to targets.go
This is purely moving code, no changes. netfilter.go is cluttered and targets.go
is a good place for this. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netfilter/netfilter.go",
"new_path": "pkg/sentry/socket/netfilter/netfilter.go",
"diff": "@@ -32,15 +32,6 @@ import (\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n-// errorTargetName is used to mark targets as error targets. Error targets\n-// shouldn't be reached - an error has occurred if we fall through to one.\n-const errorTargetName = \"ERROR\"\n-\n-// redirectTargetName is used to mark targets as redirect targets. Redirect\n-// targets should be reached for only NAT and Mangle tables. These targets will\n-// change the destination port/destination IP for packets.\n-const redirectTargetName = \"REDIRECT\"\n-\n// enableLogging controls whether to log the (de)serialization of netfilter\n// structs between userspace and netstack. These logs are useful when\n// developing iptables, but can pollute sentry logs otherwise.\n@@ -202,130 +193,6 @@ func convertNetstackToBinary(stack *stack.Stack, tablename linux.TableName) (lin\nreturn entries, info, nil\n}\n-func marshalTarget(target stack.Target) []byte {\n- switch tg := target.(type) {\n- case stack.AcceptTarget:\n- return marshalStandardTarget(stack.RuleAccept)\n- case stack.DropTarget:\n- return marshalStandardTarget(stack.RuleDrop)\n- case stack.ErrorTarget:\n- return marshalErrorTarget(errorTargetName)\n- case stack.UserChainTarget:\n- return marshalErrorTarget(tg.Name)\n- case stack.ReturnTarget:\n- return marshalStandardTarget(stack.RuleReturn)\n- case stack.RedirectTarget:\n- return marshalRedirectTarget(tg)\n- case JumpTarget:\n- return marshalJumpTarget(tg)\n- default:\n- panic(fmt.Errorf(\"unknown target of type %T\", target))\n- }\n-}\n-\n-func marshalStandardTarget(verdict stack.RuleVerdict) []byte {\n- nflog(\"convert to binary: marshalling standard target\")\n-\n- // The target's name will be the empty string.\n- target := linux.XTStandardTarget{\n- Target: linux.XTEntryTarget{\n- TargetSize: linux.SizeOfXTStandardTarget,\n- },\n- Verdict: translateFromStandardVerdict(verdict),\n- }\n-\n- ret := make([]byte, 0, linux.SizeOfXTStandardTarget)\n- return binary.Marshal(ret, usermem.ByteOrder, target)\n-}\n-\n-func marshalErrorTarget(errorName string) []byte {\n- // This is an error target named error\n- target := linux.XTErrorTarget{\n- Target: linux.XTEntryTarget{\n- TargetSize: linux.SizeOfXTErrorTarget,\n- },\n- }\n- copy(target.Name[:], errorName)\n- copy(target.Target.Name[:], errorTargetName)\n-\n- ret := make([]byte, 0, linux.SizeOfXTErrorTarget)\n- return binary.Marshal(ret, usermem.ByteOrder, target)\n-}\n-\n-func marshalRedirectTarget(rt stack.RedirectTarget) []byte {\n- // This is a redirect target named redirect\n- target := linux.XTRedirectTarget{\n- Target: linux.XTEntryTarget{\n- TargetSize: linux.SizeOfXTRedirectTarget,\n- },\n- }\n- copy(target.Target.Name[:], redirectTargetName)\n-\n- ret := make([]byte, 0, linux.SizeOfXTRedirectTarget)\n- target.NfRange.RangeSize = 1\n- if rt.RangeProtoSpecified {\n- target.NfRange.RangeIPV4.Flags |= linux.NF_NAT_RANGE_PROTO_SPECIFIED\n- }\n- // Convert port from little endian to big endian.\n- port := make([]byte, 2)\n- binary.LittleEndian.PutUint16(port, rt.MinPort)\n- target.NfRange.RangeIPV4.MinPort = binary.BigEndian.Uint16(port)\n- binary.LittleEndian.PutUint16(port, rt.MaxPort)\n- target.NfRange.RangeIPV4.MaxPort = binary.BigEndian.Uint16(port)\n- return binary.Marshal(ret, usermem.ByteOrder, target)\n-}\n-\n-func marshalJumpTarget(jt JumpTarget) []byte {\n- nflog(\"convert to binary: marshalling jump target\")\n-\n- // The target's name will be the empty string.\n- target := linux.XTStandardTarget{\n- Target: linux.XTEntryTarget{\n- TargetSize: linux.SizeOfXTStandardTarget,\n- },\n- // Verdict is overloaded by the ABI. When positive, it holds\n- // the jump offset from the start of the table.\n- Verdict: int32(jt.Offset),\n- }\n-\n- ret := make([]byte, 0, linux.SizeOfXTStandardTarget)\n- return binary.Marshal(ret, usermem.ByteOrder, target)\n-}\n-\n-// translateFromStandardVerdict translates verdicts the same way as the iptables\n-// tool.\n-func translateFromStandardVerdict(verdict stack.RuleVerdict) int32 {\n- switch verdict {\n- case stack.RuleAccept:\n- return -linux.NF_ACCEPT - 1\n- case stack.RuleDrop:\n- return -linux.NF_DROP - 1\n- case stack.RuleReturn:\n- return linux.NF_RETURN\n- default:\n- // TODO(gvisor.dev/issue/170): Support Jump.\n- panic(fmt.Sprintf(\"unknown standard verdict: %d\", verdict))\n- }\n-}\n-\n-// translateToStandardTarget translates from the value in a\n-// linux.XTStandardTarget to an stack.Verdict.\n-func translateToStandardTarget(val int32) (stack.Target, error) {\n- // TODO(gvisor.dev/issue/170): Support other verdicts.\n- switch val {\n- case -linux.NF_ACCEPT - 1:\n- return stack.AcceptTarget{}, nil\n- case -linux.NF_DROP - 1:\n- return stack.DropTarget{}, nil\n- case -linux.NF_QUEUE - 1:\n- return nil, errors.New(\"unsupported iptables verdict QUEUE\")\n- case linux.NF_RETURN:\n- return stack.ReturnTarget{}, nil\n- default:\n- return nil, fmt.Errorf(\"unknown iptables verdict %d\", val)\n- }\n-}\n-\n// SetEntries sets iptables rules for a single table. See\n// net/ipv4/netfilter/ip_tables.c:translate_table for reference.\nfunc SetEntries(stk *stack.Stack, optVal []byte) *syserr.Error {\n@@ -562,113 +429,6 @@ func parseMatchers(filter stack.IPHeaderFilter, optVal []byte) ([]stack.Matcher,\nreturn matchers, nil\n}\n-// parseTarget parses a target from optVal. optVal should contain only the\n-// target.\n-func parseTarget(filter stack.IPHeaderFilter, optVal []byte) (stack.Target, error) {\n- nflog(\"set entries: parsing target of size %d\", len(optVal))\n- if len(optVal) < linux.SizeOfXTEntryTarget {\n- return nil, fmt.Errorf(\"optVal has insufficient size for entry target %d\", len(optVal))\n- }\n- var target linux.XTEntryTarget\n- buf := optVal[:linux.SizeOfXTEntryTarget]\n- binary.Unmarshal(buf, usermem.ByteOrder, &target)\n- switch target.Name.String() {\n- case \"\":\n- // Standard target.\n- if len(optVal) != linux.SizeOfXTStandardTarget {\n- return nil, fmt.Errorf(\"optVal has wrong size for standard target %d\", len(optVal))\n- }\n- var standardTarget linux.XTStandardTarget\n- buf = optVal[:linux.SizeOfXTStandardTarget]\n- binary.Unmarshal(buf, usermem.ByteOrder, &standardTarget)\n-\n- if standardTarget.Verdict < 0 {\n- // A Verdict < 0 indicates a non-jump verdict.\n- return translateToStandardTarget(standardTarget.Verdict)\n- }\n- // A verdict >= 0 indicates a jump.\n- return JumpTarget{Offset: uint32(standardTarget.Verdict)}, nil\n-\n- case errorTargetName:\n- // Error target.\n- if len(optVal) != linux.SizeOfXTErrorTarget {\n- return nil, fmt.Errorf(\"optVal has insufficient size for error target %d\", len(optVal))\n- }\n- var errorTarget linux.XTErrorTarget\n- buf = optVal[:linux.SizeOfXTErrorTarget]\n- binary.Unmarshal(buf, usermem.ByteOrder, &errorTarget)\n-\n- // Error targets are used in 2 cases:\n- // * An actual error case. These rules have an error\n- // named errorTargetName. The last entry of the table\n- // is usually an error case to catch any packets that\n- // somehow fall through every rule.\n- // * To mark the start of a user defined chain. These\n- // rules have an error with the name of the chain.\n- switch name := errorTarget.Name.String(); name {\n- case errorTargetName:\n- nflog(\"set entries: error target\")\n- return stack.ErrorTarget{}, nil\n- default:\n- // User defined chain.\n- nflog(\"set entries: user-defined target %q\", name)\n- return stack.UserChainTarget{Name: name}, nil\n- }\n-\n- case redirectTargetName:\n- // Redirect target.\n- if len(optVal) < linux.SizeOfXTRedirectTarget {\n- return nil, fmt.Errorf(\"netfilter.SetEntries: optVal has insufficient size for redirect target %d\", len(optVal))\n- }\n-\n- if filter.Protocol != header.TCPProtocolNumber && filter.Protocol != header.UDPProtocolNumber {\n- return nil, fmt.Errorf(\"netfilter.SetEntries: invalid argument\")\n- }\n-\n- var redirectTarget linux.XTRedirectTarget\n- buf = optVal[:linux.SizeOfXTRedirectTarget]\n- binary.Unmarshal(buf, usermem.ByteOrder, &redirectTarget)\n-\n- // Copy linux.XTRedirectTarget to stack.RedirectTarget.\n- var target stack.RedirectTarget\n- nfRange := redirectTarget.NfRange\n-\n- // RangeSize should be 1.\n- if nfRange.RangeSize != 1 {\n- return nil, fmt.Errorf(\"netfilter.SetEntries: invalid argument\")\n- }\n-\n- // TODO(gvisor.dev/issue/170): Check if the flags are valid.\n- // Also check if we need to map ports or IP.\n- // For now, redirect target only supports destination port change.\n- // Port range and IP range are not supported yet.\n- if nfRange.RangeIPV4.Flags&linux.NF_NAT_RANGE_PROTO_SPECIFIED == 0 {\n- return nil, fmt.Errorf(\"netfilter.SetEntries: invalid argument\")\n- }\n- target.RangeProtoSpecified = true\n-\n- target.MinIP = tcpip.Address(nfRange.RangeIPV4.MinIP[:])\n- target.MaxIP = tcpip.Address(nfRange.RangeIPV4.MaxIP[:])\n-\n- // TODO(gvisor.dev/issue/170): Port range is not supported yet.\n- if nfRange.RangeIPV4.MinPort != nfRange.RangeIPV4.MaxPort {\n- return nil, fmt.Errorf(\"netfilter.SetEntries: invalid argument\")\n- }\n-\n- // Convert port from big endian to little endian.\n- port := make([]byte, 2)\n- binary.BigEndian.PutUint16(port, nfRange.RangeIPV4.MinPort)\n- target.MinPort = binary.LittleEndian.Uint16(port)\n-\n- binary.BigEndian.PutUint16(port, nfRange.RangeIPV4.MaxPort)\n- target.MaxPort = binary.LittleEndian.Uint16(port)\n- return target, nil\n- }\n-\n- // Unknown target.\n- return nil, fmt.Errorf(\"unknown target %q doesn't exist or isn't supported yet.\", target.Name.String())\n-}\n-\nfunc filterFromIPTIP(iptip linux.IPTIP) (stack.IPHeaderFilter, error) {\nif containsUnsupportedFields(iptip) {\nreturn stack.IPHeaderFilter{}, fmt.Errorf(\"unsupported fields in struct iptip: %+v\", iptip)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netfilter/targets.go",
"new_path": "pkg/sentry/socket/netfilter/targets.go",
"diff": "package netfilter\nimport (\n+ \"errors\"\n+ \"fmt\"\n+\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/binary\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n)\n+// errorTargetName is used to mark targets as error targets. Error targets\n+// shouldn't be reached - an error has occurred if we fall through to one.\n+const errorTargetName = \"ERROR\"\n+\n+// redirectTargetName is used to mark targets as redirect targets. Redirect\n+// targets should be reached for only NAT and Mangle tables. These targets will\n+// change the destination port/destination IP for packets.\n+const redirectTargetName = \"REDIRECT\"\n+\n+func marshalTarget(target stack.Target) []byte {\n+ switch tg := target.(type) {\n+ case stack.AcceptTarget:\n+ return marshalStandardTarget(stack.RuleAccept)\n+ case stack.DropTarget:\n+ return marshalStandardTarget(stack.RuleDrop)\n+ case stack.ErrorTarget:\n+ return marshalErrorTarget(errorTargetName)\n+ case stack.UserChainTarget:\n+ return marshalErrorTarget(tg.Name)\n+ case stack.ReturnTarget:\n+ return marshalStandardTarget(stack.RuleReturn)\n+ case stack.RedirectTarget:\n+ return marshalRedirectTarget(tg)\n+ case JumpTarget:\n+ return marshalJumpTarget(tg)\n+ default:\n+ panic(fmt.Errorf(\"unknown target of type %T\", target))\n+ }\n+}\n+\n+func marshalStandardTarget(verdict stack.RuleVerdict) []byte {\n+ nflog(\"convert to binary: marshalling standard target\")\n+\n+ // The target's name will be the empty string.\n+ target := linux.XTStandardTarget{\n+ Target: linux.XTEntryTarget{\n+ TargetSize: linux.SizeOfXTStandardTarget,\n+ },\n+ Verdict: translateFromStandardVerdict(verdict),\n+ }\n+\n+ ret := make([]byte, 0, linux.SizeOfXTStandardTarget)\n+ return binary.Marshal(ret, usermem.ByteOrder, target)\n+}\n+\n+func marshalErrorTarget(errorName string) []byte {\n+ // This is an error target named error\n+ target := linux.XTErrorTarget{\n+ Target: linux.XTEntryTarget{\n+ TargetSize: linux.SizeOfXTErrorTarget,\n+ },\n+ }\n+ copy(target.Name[:], errorName)\n+ copy(target.Target.Name[:], errorTargetName)\n+\n+ ret := make([]byte, 0, linux.SizeOfXTErrorTarget)\n+ return binary.Marshal(ret, usermem.ByteOrder, target)\n+}\n+\n+func marshalRedirectTarget(rt stack.RedirectTarget) []byte {\n+ // This is a redirect target named redirect\n+ target := linux.XTRedirectTarget{\n+ Target: linux.XTEntryTarget{\n+ TargetSize: linux.SizeOfXTRedirectTarget,\n+ },\n+ }\n+ copy(target.Target.Name[:], redirectTargetName)\n+\n+ ret := make([]byte, 0, linux.SizeOfXTRedirectTarget)\n+ target.NfRange.RangeSize = 1\n+ if rt.RangeProtoSpecified {\n+ target.NfRange.RangeIPV4.Flags |= linux.NF_NAT_RANGE_PROTO_SPECIFIED\n+ }\n+ // Convert port from little endian to big endian.\n+ port := make([]byte, 2)\n+ binary.LittleEndian.PutUint16(port, rt.MinPort)\n+ target.NfRange.RangeIPV4.MinPort = binary.BigEndian.Uint16(port)\n+ binary.LittleEndian.PutUint16(port, rt.MaxPort)\n+ target.NfRange.RangeIPV4.MaxPort = binary.BigEndian.Uint16(port)\n+ return binary.Marshal(ret, usermem.ByteOrder, target)\n+}\n+\n+func marshalJumpTarget(jt JumpTarget) []byte {\n+ nflog(\"convert to binary: marshalling jump target\")\n+\n+ // The target's name will be the empty string.\n+ target := linux.XTStandardTarget{\n+ Target: linux.XTEntryTarget{\n+ TargetSize: linux.SizeOfXTStandardTarget,\n+ },\n+ // Verdict is overloaded by the ABI. When positive, it holds\n+ // the jump offset from the start of the table.\n+ Verdict: int32(jt.Offset),\n+ }\n+\n+ ret := make([]byte, 0, linux.SizeOfXTStandardTarget)\n+ return binary.Marshal(ret, usermem.ByteOrder, target)\n+}\n+\n+// translateFromStandardVerdict translates verdicts the same way as the iptables\n+// tool.\n+func translateFromStandardVerdict(verdict stack.RuleVerdict) int32 {\n+ switch verdict {\n+ case stack.RuleAccept:\n+ return -linux.NF_ACCEPT - 1\n+ case stack.RuleDrop:\n+ return -linux.NF_DROP - 1\n+ case stack.RuleReturn:\n+ return linux.NF_RETURN\n+ default:\n+ // TODO(gvisor.dev/issue/170): Support Jump.\n+ panic(fmt.Sprintf(\"unknown standard verdict: %d\", verdict))\n+ }\n+}\n+\n+// translateToStandardTarget translates from the value in a\n+// linux.XTStandardTarget to an stack.Verdict.\n+func translateToStandardTarget(val int32) (stack.Target, error) {\n+ // TODO(gvisor.dev/issue/170): Support other verdicts.\n+ switch val {\n+ case -linux.NF_ACCEPT - 1:\n+ return stack.AcceptTarget{}, nil\n+ case -linux.NF_DROP - 1:\n+ return stack.DropTarget{}, nil\n+ case -linux.NF_QUEUE - 1:\n+ return nil, errors.New(\"unsupported iptables verdict QUEUE\")\n+ case linux.NF_RETURN:\n+ return stack.ReturnTarget{}, nil\n+ default:\n+ return nil, fmt.Errorf(\"unknown iptables verdict %d\", val)\n+ }\n+}\n+\n+// parseTarget parses a target from optVal. optVal should contain only the\n+// target.\n+func parseTarget(filter stack.IPHeaderFilter, optVal []byte) (stack.Target, error) {\n+ nflog(\"set entries: parsing target of size %d\", len(optVal))\n+ if len(optVal) < linux.SizeOfXTEntryTarget {\n+ return nil, fmt.Errorf(\"optVal has insufficient size for entry target %d\", len(optVal))\n+ }\n+ var target linux.XTEntryTarget\n+ buf := optVal[:linux.SizeOfXTEntryTarget]\n+ binary.Unmarshal(buf, usermem.ByteOrder, &target)\n+ switch target.Name.String() {\n+ case \"\":\n+ // Standard target.\n+ if len(optVal) != linux.SizeOfXTStandardTarget {\n+ return nil, fmt.Errorf(\"optVal has wrong size for standard target %d\", len(optVal))\n+ }\n+ var standardTarget linux.XTStandardTarget\n+ buf = optVal[:linux.SizeOfXTStandardTarget]\n+ binary.Unmarshal(buf, usermem.ByteOrder, &standardTarget)\n+\n+ if standardTarget.Verdict < 0 {\n+ // A Verdict < 0 indicates a non-jump verdict.\n+ return translateToStandardTarget(standardTarget.Verdict)\n+ }\n+ // A verdict >= 0 indicates a jump.\n+ return JumpTarget{Offset: uint32(standardTarget.Verdict)}, nil\n+\n+ case errorTargetName:\n+ // Error target.\n+ if len(optVal) != linux.SizeOfXTErrorTarget {\n+ return nil, fmt.Errorf(\"optVal has insufficient size for error target %d\", len(optVal))\n+ }\n+ var errorTarget linux.XTErrorTarget\n+ buf = optVal[:linux.SizeOfXTErrorTarget]\n+ binary.Unmarshal(buf, usermem.ByteOrder, &errorTarget)\n+\n+ // Error targets are used in 2 cases:\n+ // * An actual error case. These rules have an error\n+ // named errorTargetName. The last entry of the table\n+ // is usually an error case to catch any packets that\n+ // somehow fall through every rule.\n+ // * To mark the start of a user defined chain. These\n+ // rules have an error with the name of the chain.\n+ switch name := errorTarget.Name.String(); name {\n+ case errorTargetName:\n+ nflog(\"set entries: error target\")\n+ return stack.ErrorTarget{}, nil\n+ default:\n+ // User defined chain.\n+ nflog(\"set entries: user-defined target %q\", name)\n+ return stack.UserChainTarget{Name: name}, nil\n+ }\n+\n+ case redirectTargetName:\n+ // Redirect target.\n+ if len(optVal) < linux.SizeOfXTRedirectTarget {\n+ return nil, fmt.Errorf(\"netfilter.SetEntries: optVal has insufficient size for redirect target %d\", len(optVal))\n+ }\n+\n+ if filter.Protocol != header.TCPProtocolNumber && filter.Protocol != header.UDPProtocolNumber {\n+ return nil, fmt.Errorf(\"netfilter.SetEntries: invalid argument\")\n+ }\n+\n+ var redirectTarget linux.XTRedirectTarget\n+ buf = optVal[:linux.SizeOfXTRedirectTarget]\n+ binary.Unmarshal(buf, usermem.ByteOrder, &redirectTarget)\n+\n+ // Copy linux.XTRedirectTarget to stack.RedirectTarget.\n+ var target stack.RedirectTarget\n+ nfRange := redirectTarget.NfRange\n+\n+ // RangeSize should be 1.\n+ if nfRange.RangeSize != 1 {\n+ return nil, fmt.Errorf(\"netfilter.SetEntries: invalid argument\")\n+ }\n+\n+ // TODO(gvisor.dev/issue/170): Check if the flags are valid.\n+ // Also check if we need to map ports or IP.\n+ // For now, redirect target only supports destination port change.\n+ // Port range and IP range are not supported yet.\n+ if nfRange.RangeIPV4.Flags&linux.NF_NAT_RANGE_PROTO_SPECIFIED == 0 {\n+ return nil, fmt.Errorf(\"netfilter.SetEntries: invalid argument\")\n+ }\n+ target.RangeProtoSpecified = true\n+\n+ target.MinIP = tcpip.Address(nfRange.RangeIPV4.MinIP[:])\n+ target.MaxIP = tcpip.Address(nfRange.RangeIPV4.MaxIP[:])\n+\n+ // TODO(gvisor.dev/issue/170): Port range is not supported yet.\n+ if nfRange.RangeIPV4.MinPort != nfRange.RangeIPV4.MaxPort {\n+ return nil, fmt.Errorf(\"netfilter.SetEntries: invalid argument\")\n+ }\n+\n+ // Convert port from big endian to little endian.\n+ port := make([]byte, 2)\n+ binary.BigEndian.PutUint16(port, nfRange.RangeIPV4.MinPort)\n+ target.MinPort = binary.LittleEndian.Uint16(port)\n+\n+ binary.BigEndian.PutUint16(port, nfRange.RangeIPV4.MaxPort)\n+ target.MaxPort = binary.LittleEndian.Uint16(port)\n+ return target, nil\n+ }\n+\n+ // Unknown target.\n+ return nil, fmt.Errorf(\"unknown target %q doesn't exist or isn't supported yet\", target.Name.String())\n+}\n+\n// JumpTarget implements stack.Target.\ntype JumpTarget struct {\n// Offset is the byte offset of the rule to jump to. It is used for\n"
}
] | Go | Apache License 2.0 | google/gvisor | ip6tables: move target-specific code to targets.go
This is purely moving code, no changes. netfilter.go is cluttered and targets.go
is a good place for this.
#3549
PiperOrigin-RevId: 325879965 |
259,975 | 10.08.2020 14:51:07 | 25,200 | a88cf5a2e18869acb636f696700ecce2781be818 | Add benchmarks to continuous build. | [
{
"change_type": "MODIFY",
"old_path": "BUILD",
"new_path": "BUILD",
"diff": "@@ -57,6 +57,12 @@ build_test(\n\"//test/e2e:integration_test\",\n\"//test/image:image_test\",\n\"//test/root:root_test\",\n+ \"//test/benchmarks/base:base_test\",\n+ \"//test/benchmarks/database:database_test\",\n+ \"//test/benchmarks/fs:fs_test\",\n+ \"//test/benchmarks/media:media_test\",\n+ \"//test/benchmarks/ml:ml_test\",\n+ \"//test/benchmarks/network:network_test\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/base/BUILD",
"new_path": "test/benchmarks/base/BUILD",
"diff": "@@ -25,6 +25,7 @@ go_test(\n\"manual\",\n\"local\",\n],\n+ visibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/test/dockerutil\",\n\"//test/benchmarks/harness\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/database/BUILD",
"new_path": "test/benchmarks/database/BUILD",
"diff": "@@ -19,6 +19,7 @@ go_test(\n\"manual\",\n\"local\",\n],\n+ visibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/test/dockerutil\",\n\"//test/benchmarks/harness\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/fs/BUILD",
"new_path": "test/benchmarks/fs/BUILD",
"diff": "@@ -22,6 +22,7 @@ go_test(\n\"local\",\n\"manual\",\n],\n+ visibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/test/dockerutil\",\n\"//test/benchmarks/harness\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/media/BUILD",
"new_path": "test/benchmarks/media/BUILD",
"diff": "@@ -14,6 +14,7 @@ go_test(\nsize = \"large\",\nsrcs = [\"ffmpeg_test.go\"],\nlibrary = \":media\",\n+ visibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/test/dockerutil\",\n\"//test/benchmarks/harness\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/ml/BUILD",
"new_path": "test/benchmarks/ml/BUILD",
"diff": "@@ -14,6 +14,7 @@ go_test(\nsize = \"large\",\nsrcs = [\"tensorflow_test.go\"],\nlibrary = \":ml\",\n+ visibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/test/dockerutil\",\n\"//test/benchmarks/harness\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/network/BUILD",
"new_path": "test/benchmarks/network/BUILD",
"diff": "@@ -25,6 +25,7 @@ go_test(\n\"manual\",\n\"local\",\n],\n+ visibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/test/dockerutil\",\n\"//pkg/test/testutil\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add benchmarks to continuous build.
PiperOrigin-RevId: 325892974 |
259,907 | 10.08.2020 15:48:24 | 25,200 | a1af46c20ade5566ca8c2583f10c17765a5dc3ad | Enable VFS2 by default for all syscall tests.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "test/runner/defs.bzl",
"new_path": "test/runner/defs.bzl",
"diff": "@@ -132,7 +132,7 @@ def syscall_test(\nadd_overlay = False,\nadd_uds_tree = False,\nadd_hostinet = False,\n- vfs2 = False,\n+ vfs2 = True,\nfuse = False,\ntags = None):\n\"\"\"syscall_test is a macro that will create targets for all platforms.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -4,75 +4,62 @@ package(licenses = [\"notice\"])\nsyscall_test(\ntest = \"//test/syscalls/linux:32bit_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:accept_bind_stream_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"large\",\nshard_count = 50,\ntest = \"//test/syscalls/linux:accept_bind_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:access_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:affinity_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:aio_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nshard_count = 5,\ntest = \"//test/syscalls/linux:alarm_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:arch_prctl_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:bad_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"large\",\nadd_overlay = True,\ntest = \"//test/syscalls/linux:bind_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:brk_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:socket_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:socket_capability_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\n@@ -82,19 +69,16 @@ syscall_test(\n# involve much concurrency, TSAN's usefulness here is limited anyway.\ntags = [\"nogotsan\"],\ntest = \"//test/syscalls/linux:socket_stress_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:chdir_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:chmod_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\n@@ -102,116 +86,96 @@ syscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:chown_test\",\nuse_tmpfs = True, # chwon tests require gofer to be running as root.\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:chroot_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:clock_getres_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:clock_gettime_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:clock_nanosleep_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:concurrency_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_uds_tree = True,\ntest = \"//test/syscalls/linux:connect_external_test\",\nuse_tmpfs = True,\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:creat_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nfuse = \"True\",\ntest = \"//test/syscalls/linux:dev_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:dup_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:epoll_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:eventfd_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:exceptions_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nadd_overlay = True,\ntest = \"//test/syscalls/linux:exec_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nadd_overlay = True,\ntest = \"//test/syscalls/linux:exec_binary_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:exit_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:fadvise64_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:fallocate_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:fault_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:fchdir_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\n@@ -223,204 +187,168 @@ syscall_test(\nsize = \"medium\",\nadd_overlay = True,\ntest = \"//test/syscalls/linux:flock_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:fork_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:fpsig_fork_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:fpsig_nested_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:fsync_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nshard_count = 5,\ntest = \"//test/syscalls/linux:futex_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:getcpu_host_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:getcpu_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:getdents_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:getrandom_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:getrusage_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nadd_overlay = False, # TODO(gvisor.dev/issue/317): enable when fixed.\ntest = \"//test/syscalls/linux:inotify_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nadd_overlay = True,\ntest = \"//test/syscalls/linux:ioctl_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:iptables_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"large\",\nshard_count = 5,\ntest = \"//test/syscalls/linux:itimer_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:kill_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:link_test\",\nuse_tmpfs = True, # gofer needs CAP_DAC_READ_SEARCH to use AT_EMPTY_PATH with linkat(2)\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:lseek_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:madvise_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:memory_accounting_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:mempolicy_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:mincore_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:mkdir_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:mknod_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nshard_count = 5,\ntest = \"//test/syscalls/linux:mmap_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:mount_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:mremap_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:msync_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:munmap_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:network_namespace_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:open_create_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:open_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:packet_socket_raw_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:packet_socket_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:partial_bad_buffer_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:pause_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\n@@ -428,7 +356,6 @@ syscall_test(\n# Takes too long under gotsan to run.\ntags = [\"nogotsan\"],\ntest = \"//test/syscalls/linux:ping_socket_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\n@@ -436,229 +363,188 @@ syscall_test(\nadd_overlay = True,\nshard_count = 5,\ntest = \"//test/syscalls/linux:pipe_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:poll_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:ppoll_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:prctl_setuid_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:prctl_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:pread64_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:preadv_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:preadv2_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:priority_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:proc_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:proc_net_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:proc_pid_oomscore_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:proc_pid_smaps_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:proc_pid_uid_gid_map_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:pselect_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:ptrace_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nshard_count = 5,\ntest = \"//test/syscalls/linux:pty_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:pty_root_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:pwritev2_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:pwrite64_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:raw_socket_hdrincl_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:raw_socket_icmp_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:raw_socket_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:read_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:readahead_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nshard_count = 5,\ntest = \"//test/syscalls/linux:readv_socket_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nadd_overlay = True,\ntest = \"//test/syscalls/linux:readv_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nadd_overlay = True,\ntest = \"//test/syscalls/linux:rename_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:rlimits_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:rseq_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:rtsignal_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:signalfd_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:sched_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:sched_yield_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:seccomp_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:select_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nshard_count = 20,\ntest = \"//test/syscalls/linux:semaphore_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:sendfile_socket_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:sendfile_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:splice_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:sigaction_test\",\n- vfs2 = \"True\",\n)\n# TODO(b/119826902): Enable once the test passes in runsc.\n@@ -666,62 +552,52 @@ syscall_test(\nsyscall_test(\ntest = \"//test/syscalls/linux:sigiret_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:sigprocmask_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:sigstop_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:sigtimedwait_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:shm_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:socket_abstract_non_blocking_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"large\",\nshard_count = 50,\ntest = \"//test/syscalls/linux:socket_abstract_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:socket_domain_non_blocking_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"large\",\nshard_count = 50,\ntest = \"//test/syscalls/linux:socket_domain_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nadd_overlay = True,\ntest = \"//test/syscalls/linux:socket_filesystem_non_blocking_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\n@@ -729,14 +605,12 @@ syscall_test(\nadd_overlay = True,\nshard_count = 50,\ntest = \"//test/syscalls/linux:socket_filesystem_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"large\",\nshard_count = 50,\ntest = \"//test/syscalls/linux:socket_inet_loopback_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\n@@ -745,122 +619,101 @@ syscall_test(\n# Takes too long for TSAN. Creates a lot of TCP sockets.\ntags = [\"nogotsan\"],\ntest = \"//test/syscalls/linux:socket_inet_loopback_nogotsan_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"large\",\nshard_count = 50,\ntest = \"//test/syscalls/linux:socket_ip_tcp_generic_loopback_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:socket_ip_tcp_loopback_non_blocking_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"large\",\nshard_count = 50,\ntest = \"//test/syscalls/linux:socket_ip_tcp_loopback_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nshard_count = 50,\ntest = \"//test/syscalls/linux:socket_ip_tcp_udp_generic_loopback_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:socket_ip_udp_loopback_non_blocking_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"large\",\nshard_count = 50,\ntest = \"//test/syscalls/linux:socket_ip_udp_loopback_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:socket_ipv4_udp_unbound_loopback_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:socket_ip_unbound_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:socket_netdevice_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:socket_netlink_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:socket_netlink_route_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:socket_netlink_uevent_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:socket_blocking_local_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:socket_blocking_ip_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:socket_non_stream_blocking_local_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:socket_non_stream_blocking_udp_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"large\",\ntest = \"//test/syscalls/linux:socket_stream_blocking_local_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"large\",\ntest = \"//test/syscalls/linux:socket_stream_blocking_tcp_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:socket_stream_local_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:socket_stream_nonblock_local_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\n@@ -868,13 +721,11 @@ syscall_test(\nsize = \"enormous\",\nshard_count = 5,\ntest = \"//test/syscalls/linux:socket_unix_dgram_local_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:socket_unix_dgram_non_blocking_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\n@@ -882,7 +733,6 @@ syscall_test(\nadd_overlay = True,\nshard_count = 50,\ntest = \"//test/syscalls/linux:socket_unix_pair_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\n@@ -890,156 +740,129 @@ syscall_test(\nsize = \"enormous\",\nshard_count = 5,\ntest = \"//test/syscalls/linux:socket_unix_seqpacket_local_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:socket_unix_stream_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:socket_unix_unbound_abstract_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:socket_unix_unbound_dgram_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:socket_unix_unbound_filesystem_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nshard_count = 10,\ntest = \"//test/syscalls/linux:socket_unix_unbound_seqpacket_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"large\",\nshard_count = 50,\ntest = \"//test/syscalls/linux:socket_unix_unbound_stream_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:statfs_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:stat_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:stat_times_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:sticky_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:symlink_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:sync_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:sync_file_range_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:sysinfo_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:syslog_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:sysret_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nshard_count = 10,\ntest = \"//test/syscalls/linux:tcp_socket_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:tgkill_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:timerfd_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:timers_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:time_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:tkill_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:truncate_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:tuntap_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_hostinet = True,\ntest = \"//test/syscalls/linux:tuntap_hostinet_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:udp_bind_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\n@@ -1047,80 +870,65 @@ syscall_test(\nadd_hostinet = True,\nshard_count = 10,\ntest = \"//test/syscalls/linux:udp_socket_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:uidgid_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:uname_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:unlink_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:unshare_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:utimes_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:vdso_clock_gettime_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:vdso_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:vsyscall_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:vfork_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nsize = \"medium\",\nshard_count = 5,\ntest = \"//test/syscalls/linux:wait_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:write_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:proc_net_unix_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:proc_net_tcp_test\",\n- vfs2 = \"True\",\n)\nsyscall_test(\ntest = \"//test/syscalls/linux:proc_net_udp_test\",\n- vfs2 = \"True\",\n)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable VFS2 by default for all syscall tests.
Fixes #2923
PiperOrigin-RevId: 325904734 |
260,004 | 10.08.2020 16:20:39 | 25,200 | 0a8ae4b32f0dbc0b2a84c3f07c8c98e855a8f5fa | Populate IPPacketInfo with destination address
IPPacketInfo.DestinationAddr should hold the destination of the IP
packet, not the source. This change fixes that bug. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/checker/BUILD",
"new_path": "pkg/tcpip/checker/BUILD",
"diff": "@@ -12,5 +12,6 @@ go_library(\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/seqnum\",\n+ \"@com_github_google_go_cmp//cmp:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/checker/checker.go",
"new_path": "pkg/tcpip/checker/checker.go",
"diff": "@@ -21,6 +21,7 @@ import (\n\"reflect\"\n\"testing\"\n+ \"github.com/google/go-cmp/cmp\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n@@ -169,10 +170,9 @@ func ReceiveTClass(want uint32) ControlMessagesChecker {\nreturn func(t *testing.T, cm tcpip.ControlMessages) {\nt.Helper()\nif !cm.HasTClass {\n- t.Fatalf(\"got cm.HasTClass = %t, want cm.TClass = %d\", cm.HasTClass, want)\n- }\n- if got := cm.TClass; got != want {\n- t.Fatalf(\"got cm.TClass = %d, want %d\", got, want)\n+ t.Errorf(\"got cm.HasTClass = %t, want = true\", cm.HasTClass)\n+ } else if got := cm.TClass; got != want {\n+ t.Errorf(\"got cm.TClass = %d, want %d\", got, want)\n}\n}\n}\n@@ -182,10 +182,22 @@ func ReceiveTOS(want uint8) ControlMessagesChecker {\nreturn func(t *testing.T, cm tcpip.ControlMessages) {\nt.Helper()\nif !cm.HasTOS {\n- t.Fatalf(\"got cm.HasTOS = %t, want cm.TOS = %d\", cm.HasTOS, want)\n+ t.Errorf(\"got cm.HasTOS = %t, want = true\", cm.HasTOS)\n+ } else if got := cm.TOS; got != want {\n+ t.Errorf(\"got cm.TOS = %d, want %d\", got, want)\n+ }\n}\n- if got := cm.TOS; got != want {\n- t.Fatalf(\"got cm.TOS = %d, want %d\", got, want)\n+}\n+\n+// ReceiveIPPacketInfo creates a checker that checks the PacketInfo field in\n+// ControlMessages.\n+func ReceiveIPPacketInfo(want tcpip.IPPacketInfo) ControlMessagesChecker {\n+ return func(t *testing.T, cm tcpip.ControlMessages) {\n+ t.Helper()\n+ if !cm.HasIPPacketInfo {\n+ t.Errorf(\"got cm.HasIPPacketInfo = %t, want = true\", cm.HasIPPacketInfo)\n+ } else if diff := cmp.Diff(want, cm.PacketInfo); diff != \"\" {\n+ t.Errorf(\"IPPacketInfo mismatch (-want +got):\\n%s\", diff)\n}\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -968,7 +968,7 @@ type IPPacketInfo struct {\n// LocalAddr is the local address.\nLocalAddr Address\n- // DestinationAddr is the destination address.\n+ // DestinationAddr is the destination address found in the IP header.\nDestinationAddr Address\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -1444,13 +1444,16 @@ func (e *endpoint) HandlePacket(r *stack.Route, id stack.TransportEndpointID, pk\nswitch r.NetProto {\ncase header.IPv4ProtocolNumber:\npacket.tos, _ = header.IPv4(pkt.NetworkHeader).TOS()\n- packet.packetInfo.LocalAddr = r.LocalAddress\n- packet.packetInfo.DestinationAddr = r.RemoteAddress\n- packet.packetInfo.NIC = r.NICID()\ncase header.IPv6ProtocolNumber:\npacket.tos, _ = header.IPv6(pkt.NetworkHeader).TOS()\n}\n+ // TODO(gvisor.dev/issue/3556): r.LocalAddress may be a multicast or broadcast\n+ // address. packetInfo.LocalAddr should hold a unicast address that can be\n+ // used to respond to the incoming packet.\n+ packet.packetInfo.LocalAddr = r.LocalAddress\n+ packet.packetInfo.DestinationAddr = r.LocalAddress\n+ packet.packetInfo.NIC = r.NICID()\npacket.timestamp = e.stack.Clock().NowNanoseconds()\ne.rcvMu.Unlock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/udp_test.go",
"new_path": "pkg/tcpip/transport/udp/udp_test.go",
"diff": "@@ -1309,6 +1309,105 @@ func TestReadIncrementsPacketsReceived(t *testing.T) {\n}\n}\n+func TestReadIPPacketInfo(t *testing.T) {\n+ tests := []struct {\n+ name string\n+ proto tcpip.NetworkProtocolNumber\n+ flow testFlow\n+ expectedLocalAddr tcpip.Address\n+ expectedDestAddr tcpip.Address\n+ }{\n+ {\n+ name: \"IPv4 unicast\",\n+ proto: header.IPv4ProtocolNumber,\n+ flow: unicastV4,\n+ expectedLocalAddr: stackAddr,\n+ expectedDestAddr: stackAddr,\n+ },\n+ {\n+ name: \"IPv4 multicast\",\n+ proto: header.IPv4ProtocolNumber,\n+ flow: multicastV4,\n+ // This should actually be a unicast address assigned to the interface.\n+ //\n+ // TODO(gvisor.dev/issue/3556): This check is validating incorrect\n+ // behaviour. We still include the test so that once the bug is\n+ // resolved, this test will start to fail and the individual tasked\n+ // with fixing this bug knows to also fix this test :).\n+ expectedLocalAddr: multicastAddr,\n+ expectedDestAddr: multicastAddr,\n+ },\n+ {\n+ name: \"IPv4 broadcast\",\n+ proto: header.IPv4ProtocolNumber,\n+ flow: broadcast,\n+ // This should actually be a unicast address assigned to the interface.\n+ //\n+ // TODO(gvisor.dev/issue/3556): This check is validating incorrect\n+ // behaviour. We still include the test so that once the bug is\n+ // resolved, this test will start to fail and the individual tasked\n+ // with fixing this bug knows to also fix this test :).\n+ expectedLocalAddr: broadcastAddr,\n+ expectedDestAddr: broadcastAddr,\n+ },\n+ {\n+ name: \"IPv6 unicast\",\n+ proto: header.IPv6ProtocolNumber,\n+ flow: unicastV6,\n+ expectedLocalAddr: stackV6Addr,\n+ expectedDestAddr: stackV6Addr,\n+ },\n+ {\n+ name: \"IPv6 multicast\",\n+ proto: header.IPv6ProtocolNumber,\n+ flow: multicastV6,\n+ // This should actually be a unicast address assigned to the interface.\n+ //\n+ // TODO(gvisor.dev/issue/3556): This check is validating incorrect\n+ // behaviour. We still include the test so that once the bug is\n+ // resolved, this test will start to fail and the individual tasked\n+ // with fixing this bug knows to also fix this test :).\n+ expectedLocalAddr: multicastV6Addr,\n+ expectedDestAddr: multicastV6Addr,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ c := newDualTestContext(t, defaultMTU)\n+ defer c.cleanup()\n+\n+ c.createEndpoint(test.proto)\n+\n+ bindAddr := tcpip.FullAddress{Port: stackPort}\n+ if err := c.ep.Bind(bindAddr); err != nil {\n+ t.Fatalf(\"Bind(%+v): %s\", bindAddr, err)\n+ }\n+\n+ if test.flow.isMulticast() {\n+ ifoptSet := tcpip.AddMembershipOption{NIC: 1, MulticastAddr: test.flow.getMcastAddr()}\n+ if err := c.ep.SetSockOpt(ifoptSet); err != nil {\n+ c.t.Fatalf(\"SetSockOpt(%+v): %s:\", ifoptSet, err)\n+ }\n+ }\n+\n+ if err := c.ep.SetSockOptBool(tcpip.ReceiveIPPacketInfoOption, true); err != nil {\n+ t.Fatalf(\"c.ep.SetSockOptBool(tcpip.ReceiveIPPacketInfoOption, true): %s\", err)\n+ }\n+\n+ testRead(c, test.flow, checker.ReceiveIPPacketInfo(tcpip.IPPacketInfo{\n+ NIC: 1,\n+ LocalAddr: test.expectedLocalAddr,\n+ DestinationAddr: test.expectedDestAddr,\n+ }))\n+\n+ if got := c.s.Stats().UDP.PacketsReceived.Value(); got != 1 {\n+ t.Fatalf(\"Read did not increment PacketsReceived: got = %d, want = 1\", got)\n+ }\n+ })\n+ }\n+}\n+\nfunc TestWriteIncrementsPacketsSent(t *testing.T) {\nc := newDualTestContext(t, defaultMTU)\ndefer c.cleanup()\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": "@@ -2452,5 +2452,105 @@ TEST_P(IPv4UDPUnboundSocketTest, SetSocketSendBuf) {\nASSERT_EQ(quarter_sz, val);\n}\n+\n+TEST_P(IPv4UDPUnboundSocketTest, IpMulticastIPPacketInfo) {\n+ auto sender_socket = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+ auto receiver_socket = 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(sender_socket->get(), reinterpret_cast<sockaddr*>(&sender_addr.addr),\n+ 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(receiver_socket->get(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\n+ SyscallSucceeds());\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ ASSERT_THAT(getsockname(receiver_socket->get(),\n+ reinterpret_cast<sockaddr*>(&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(InterfaceIndex(\"lo\"));\n+ ASSERT_THAT(setsockopt(receiver_socket->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n+ &group, sizeof(group)),\n+ SyscallSucceeds());\n+\n+ // Register to receive IP packet info.\n+ const int one = 1;\n+ ASSERT_THAT(setsockopt(receiver_socket->get(), IPPROTO_IP, IP_PKTINFO, &one,\n+ sizeof(one)),\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)(sender_socket->get(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&send_addr.addr),\n+ send_addr.addr_len),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ // Check that we received the multicast packet.\n+ msghdr recv_msg = {};\n+ iovec recv_iov = {};\n+ char recv_buf[sizeof(send_buf)];\n+ char recv_cmsg_buf[CMSG_SPACE(sizeof(in_pktinfo))] = {};\n+ size_t cmsg_data_len = sizeof(in_pktinfo);\n+ recv_iov.iov_base = recv_buf;\n+ recv_iov.iov_len = sizeof(recv_buf);\n+ recv_msg.msg_iov = &recv_iov;\n+ recv_msg.msg_iovlen = 1;\n+ recv_msg.msg_controllen = CMSG_LEN(cmsg_data_len);\n+ recv_msg.msg_control = recv_cmsg_buf;\n+ ASSERT_THAT(RetryEINTR(recvmsg)(receiver_socket->get(), &recv_msg, 0),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+ EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n+\n+ // Check the IP_PKTINFO control message.\n+ cmsghdr* cmsg = CMSG_FIRSTHDR(&recv_msg);\n+ ASSERT_NE(cmsg, nullptr);\n+ EXPECT_EQ(cmsg->cmsg_len, CMSG_LEN(cmsg_data_len));\n+ EXPECT_EQ(cmsg->cmsg_level, IPPROTO_IP);\n+ EXPECT_EQ(cmsg->cmsg_type, IP_PKTINFO);\n+\n+ // Get loopback index.\n+ ifreq ifr = {};\n+ absl::SNPrintF(ifr.ifr_name, IFNAMSIZ, \"lo\");\n+ ASSERT_THAT(ioctl(receiver_socket->get(), SIOCGIFINDEX, &ifr),\n+ SyscallSucceeds());\n+ ASSERT_NE(ifr.ifr_ifindex, 0);\n+\n+ in_pktinfo received_pktinfo = {};\n+ memcpy(&received_pktinfo, CMSG_DATA(cmsg), sizeof(in_pktinfo));\n+ EXPECT_EQ(received_pktinfo.ipi_ifindex, ifr.ifr_ifindex);\n+ if (IsRunningOnGvisor()) {\n+ // This should actually be a unicast address assigned to the interface.\n+ //\n+ // TODO(gvisor.dev/issue/3556): This check is validating incorrect\n+ // behaviour. We still include the test so that once the bug is\n+ // resolved, this test will start to fail and the individual tasked\n+ // with fixing this bug knows to also fix this test :).\n+ EXPECT_EQ(received_pktinfo.ipi_spec_dst.s_addr, group.imr_multiaddr.s_addr);\n+ } else {\n+ EXPECT_EQ(received_pktinfo.ipi_spec_dst.s_addr, htonl(INADDR_LOOPBACK));\n+ }\n+ EXPECT_EQ(received_pktinfo.ipi_addr.s_addr, group.imr_multiaddr.s_addr);\n+}\n+\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Populate IPPacketInfo with destination address
IPPacketInfo.DestinationAddr should hold the destination of the IP
packet, not the source. This change fixes that bug.
PiperOrigin-RevId: 325910766 |
259,983 | 10.08.2020 18:15:32 | 25,200 | 51e64d2fc590b0271d4e0cbbc75882cf81ada182 | Implement FUSE_GETATTR
FUSE_GETATTR is called when a stat(2), fstat(2), or lstat(2) is issued
from VFS2 layer to a FUSE filesystem.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/fuse.go",
"new_path": "pkg/abi/linux/fuse.go",
"diff": "@@ -246,3 +246,58 @@ type FUSEInitOut struct {\n_ [8]uint32\n}\n+\n+// FUSEGetAttrIn is the request sent by the kernel to the daemon,\n+// to get the attribute of a inode.\n+//\n+// +marshal\n+type FUSEGetAttrIn struct {\n+ // GetAttrFlags specifies whether getattr request is sent with a nodeid or\n+ // with a file handle.\n+ GetAttrFlags uint32\n+\n+ _ uint32\n+\n+ // Fh is the file handler when GetAttrFlags has FUSE_GETATTR_FH bit. If\n+ // used, the operation is analogous to fstat(2).\n+ Fh uint64\n+}\n+\n+// FUSEAttr is the struct used in the reponse FUSEGetAttrOut.\n+//\n+// +marshal\n+type FUSEAttr struct {\n+ Ino uint64\n+ Size uint64\n+ Blocks uint64\n+ Atime uint64\n+ Mtime uint64\n+ Ctime uint64\n+ AtimeNsec uint32\n+ MtimeNsec uint32\n+ CtimeNsec uint32\n+ Mode uint32\n+ Nlink uint32\n+ UID uint32\n+ GID uint32\n+ Rdev uint32\n+ BlkSize uint32\n+ _ uint32\n+}\n+\n+// FUSEGetAttrOut is the reply sent by the daemon to the kernel\n+// for FUSEGetAttrIn.\n+//\n+// +marshal\n+type FUSEGetAttrOut struct {\n+ // AttrValid and AttrValidNsec describe the attribute cache duration\n+ AttrValid uint64\n+\n+ // AttrValidNsec is the nanosecond part of the attribute cache duration\n+ AttrValidNsec uint32\n+\n+ _ uint32\n+\n+ // Attr contains the metadata returned from the FUSE server\n+ Attr FUSEAttr\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/fusefs.go",
"new_path": "pkg/sentry/fsimpl/fuse/fusefs.go",
"diff": "@@ -226,3 +226,99 @@ func (i *inode) Open(ctx context.Context, rp *vfs.ResolvingPath, vfsd *vfs.Dentr\n}\nreturn fd.VFSFileDescription(), nil\n}\n+\n+// statFromFUSEAttr makes attributes from linux.FUSEAttr to linux.Statx. The\n+// opts.Sync attribute is ignored since the synchronization is handled by the\n+// FUSE server.\n+func statFromFUSEAttr(attr linux.FUSEAttr, mask, devMinor uint32) linux.Statx {\n+ var stat linux.Statx\n+ stat.Blksize = attr.BlkSize\n+ stat.DevMajor, stat.DevMinor = linux.UNNAMED_MAJOR, devMinor\n+\n+ rdevMajor, rdevMinor := linux.DecodeDeviceID(attr.Rdev)\n+ stat.RdevMajor, stat.RdevMinor = uint32(rdevMajor), rdevMinor\n+\n+ if mask&linux.STATX_MODE != 0 {\n+ stat.Mode = uint16(attr.Mode)\n+ }\n+ if mask&linux.STATX_NLINK != 0 {\n+ stat.Nlink = attr.Nlink\n+ }\n+ if mask&linux.STATX_UID != 0 {\n+ stat.UID = attr.UID\n+ }\n+ if mask&linux.STATX_GID != 0 {\n+ stat.GID = attr.GID\n+ }\n+ if mask&linux.STATX_ATIME != 0 {\n+ stat.Atime = linux.StatxTimestamp{\n+ Sec: int64(attr.Atime),\n+ Nsec: attr.AtimeNsec,\n+ }\n+ }\n+ if mask&linux.STATX_MTIME != 0 {\n+ stat.Mtime = linux.StatxTimestamp{\n+ Sec: int64(attr.Mtime),\n+ Nsec: attr.MtimeNsec,\n+ }\n+ }\n+ if mask&linux.STATX_CTIME != 0 {\n+ stat.Ctime = linux.StatxTimestamp{\n+ Sec: int64(attr.Ctime),\n+ Nsec: attr.CtimeNsec,\n+ }\n+ }\n+ if mask&linux.STATX_INO != 0 {\n+ stat.Ino = attr.Ino\n+ }\n+ if mask&linux.STATX_SIZE != 0 {\n+ stat.Size = attr.Size\n+ }\n+ if mask&linux.STATX_BLOCKS != 0 {\n+ stat.Blocks = attr.Blocks\n+ }\n+ return stat\n+}\n+\n+// Stat implements kernfs.Inode.Stat.\n+func (i *inode) Stat(ctx context.Context, fs *vfs.Filesystem, opts vfs.StatOptions) (linux.Statx, error) {\n+ fusefs := fs.Impl().(*filesystem)\n+ conn := fusefs.conn\n+ task, creds := kernel.TaskFromContext(ctx), auth.CredentialsFromContext(ctx)\n+ if task == nil {\n+ log.Warningf(\"couldn't get kernel task from context\")\n+ return linux.Statx{}, syserror.EINVAL\n+ }\n+\n+ var in linux.FUSEGetAttrIn\n+ // We don't set any attribute in the request, because in VFS2 fstat(2) will\n+ // finally be translated into vfs.FilesystemImpl.StatAt() (see\n+ // pkg/sentry/syscalls/linux/vfs2/stat.go), resulting in the same flow\n+ // as stat(2). Thus GetAttrFlags and Fh variable will never be used in VFS2.\n+ req, err := conn.NewRequest(creds, uint32(task.ThreadID()), i.Ino(), linux.FUSE_GETATTR, &in)\n+ if err != nil {\n+ return linux.Statx{}, err\n+ }\n+\n+ res, err := conn.Call(task, req)\n+ if err != nil {\n+ return linux.Statx{}, err\n+ }\n+ if err := res.Error(); err != nil {\n+ return linux.Statx{}, err\n+ }\n+\n+ var out linux.FUSEGetAttrOut\n+ if err := res.UnmarshalPayload(&out); err != nil {\n+ return linux.Statx{}, err\n+ }\n+\n+ // Set all metadata into kernfs.InodeAttrs.\n+ if err := i.SetStat(ctx, fs, creds, vfs.SetStatOptions{\n+ Stat: statFromFUSEAttr(out.Attr, linux.STATX_ALL, fusefs.devMinor),\n+ }); err != nil {\n+ return linux.Statx{}, err\n+ }\n+\n+ return statFromFUSEAttr(out.Attr, opts.Mask, fusefs.devMinor), nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/fuse/BUILD",
"new_path": "test/fuse/BUILD",
"diff": "+load(\"//test/runner:defs.bzl\", \"syscall_test\")\n+\npackage(licenses = [\"notice\"])\n+\n+syscall_test(\n+ fuse = \"True\",\n+ test = \"//test/fuse/linux:stat_test\",\n+ vfs2 = \"True\",\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/fuse/linux/BUILD",
"new_path": "test/fuse/linux/BUILD",
"diff": "-load(\"//tools:defs.bzl\", \"cc_library\", \"gtest\")\n+load(\"//tools:defs.bzl\", \"cc_binary\", \"cc_library\", \"gtest\")\npackage(\ndefault_visibility = [\"//:sandbox\"],\nlicenses = [\"notice\"],\n)\n+cc_binary(\n+ name = \"stat_test\",\n+ testonly = 1,\n+ srcs = [\"stat_test.cc\"],\n+ deps = [\n+ gtest,\n+ \":fuse_base\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_library(\nname = \"fuse_base\",\ntestonly = 1,\n- srcs = [\n- \"fuse_base.cc\",\n- \"fuse_base.h\",\n- ],\n+ srcs = [\"fuse_base.cc\"],\n+ hdrs = [\"fuse_base.h\"],\ndeps = [\ngtest,\n\"//test/util:posix_error\",\n+ \"//test/util:temp_path\",\n\"//test/util:test_util\",\n\"@com_google_absl//absl/strings:str_format\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "test/fuse/linux/fuse_base.cc",
"new_path": "test/fuse/linux/fuse_base.cc",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-#include \"fuse_base.h\"\n+#include \"test/fuse/linux/fuse_base.h\"\n#include <fcntl.h>\n#include <linux/fuse.h>\n-#include <stdio.h>\n#include <string.h>\n#include <sys/mount.h>\n#include <sys/stat.h>\n+#include <sys/types.h>\n#include <sys/uio.h>\n#include <unistd.h>\n#include <iostream>\n-#include \"gmock/gmock.h\"\n-#include \"gtest/gtest.h\"\n#include \"absl/strings/str_format.h\"\n+#include \"gtest/gtest.h\"\n#include \"test/util/posix_error.h\"\n+#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\nnamespace gvisor {\n@@ -78,13 +78,14 @@ void FuseTest::MountFuse() {\nEXPECT_THAT(dev_fd_ = open(\"/dev/fuse\", O_RDWR), SyscallSucceeds());\nstd::string mount_opts = absl::StrFormat(\"fd=%d,%s\", dev_fd_, kMountOpts);\n- EXPECT_THAT(mount(\"fuse\", kMountPoint, \"fuse\", MS_NODEV | MS_NOSUID,\n- mount_opts.c_str()),\n+ mount_point_ = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ EXPECT_THAT(mount(\"fuse\", mount_point_.path().c_str(), \"fuse\",\n+ MS_NODEV | MS_NOSUID, mount_opts.c_str()),\nSyscallSucceedsWithValue(0));\n}\nvoid FuseTest::UnmountFuse() {\n- EXPECT_THAT(umount(kMountPoint), SyscallSucceeds());\n+ EXPECT_THAT(umount(mount_point_.path().c_str()), SyscallSucceeds());\n// TODO(gvisor.dev/issue/3330): ensure the process is terminated successfully.\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/fuse/linux/fuse_base.h",
"new_path": "test/fuse/linux/fuse_base.h",
"diff": "#include <vector>\n-#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n#include \"test/util/posix_error.h\"\n+#include \"test/util/temp_path.h\"\nnamespace gvisor {\nnamespace testing {\n-constexpr char kMountPoint[] = \"/mnt\";\nconstexpr char kMountOpts[] = \"rootmode=755,user_id=0,group_id=0\";\nclass FuseTest : public ::testing::Test {\n@@ -55,6 +54,9 @@ class FuseTest : public ::testing::Test {\n// complains if the FUSE server responds failure during tests.\nvoid WaitCompleted();\n+ protected:\n+ TempPath mount_point_;\n+\nprivate:\nvoid MountFuse();\nvoid UnmountFuse();\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/fuse/linux/stat_test.cc",
"diff": "+// Copyright 2020 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 <fcntl.h>\n+#include <linux/fuse.h>\n+#include <sys/stat.h>\n+#include <sys/statfs.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include <vector>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class StatTest : public FuseTest {\n+ public:\n+ bool CompareRequest(void* expected_mem, size_t expected_len, void* real_mem,\n+ size_t real_len) override {\n+ if (expected_len != real_len) return false;\n+ struct fuse_in_header* real_header =\n+ reinterpret_cast<fuse_in_header*>(real_mem);\n+\n+ if (real_header->opcode != FUSE_GETATTR) {\n+ std::cerr << \"expect header opcode \" << FUSE_GETATTR << \" but got \"\n+ << real_header->opcode << std::endl;\n+ return false;\n+ }\n+ return true;\n+ }\n+\n+ bool StatsAreEqual(struct stat expected, struct stat actual) {\n+ // device number will be dynamically allocated by kernel, we cannot know\n+ // in advance\n+ actual.st_dev = expected.st_dev;\n+ return memcmp(&expected, &actual, sizeof(struct stat)) == 0;\n+ }\n+};\n+\n+TEST_F(StatTest, StatNormal) {\n+ struct iovec iov_in[2];\n+ struct iovec iov_out[2];\n+\n+ struct fuse_in_header in_header = {\n+ .len = sizeof(struct fuse_in_header) + sizeof(struct fuse_getattr_in),\n+ .opcode = FUSE_GETATTR,\n+ .unique = 4,\n+ .nodeid = 1,\n+ .uid = 0,\n+ .gid = 0,\n+ .pid = 4,\n+ .padding = 0,\n+ };\n+ struct fuse_getattr_in in_payload = {0};\n+ iov_in[0].iov_len = sizeof(in_header);\n+ iov_in[0].iov_base = &in_header;\n+ iov_in[1].iov_len = sizeof(in_payload);\n+ iov_in[1].iov_base = &in_payload;\n+\n+ mode_t expected_mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;\n+ struct timespec atime = {.tv_sec = 1595436289, .tv_nsec = 134150844};\n+ struct timespec mtime = {.tv_sec = 1595436290, .tv_nsec = 134150845};\n+ struct timespec ctime = {.tv_sec = 1595436291, .tv_nsec = 134150846};\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n+ .error = 0,\n+ .unique = 4,\n+ };\n+ struct fuse_attr attr = {\n+ .ino = 1,\n+ .size = 512,\n+ .blocks = 4,\n+ .atime = static_cast<uint64_t>(atime.tv_sec),\n+ .mtime = static_cast<uint64_t>(mtime.tv_sec),\n+ .ctime = static_cast<uint64_t>(ctime.tv_sec),\n+ .atimensec = static_cast<uint32_t>(atime.tv_nsec),\n+ .mtimensec = static_cast<uint32_t>(mtime.tv_nsec),\n+ .ctimensec = static_cast<uint32_t>(ctime.tv_nsec),\n+ .mode = expected_mode,\n+ .nlink = 2,\n+ .uid = 1234,\n+ .gid = 4321,\n+ .rdev = 12,\n+ .blksize = 4096,\n+ };\n+ struct fuse_attr_out out_payload = {\n+ .attr = attr,\n+ };\n+ iov_out[0].iov_len = sizeof(out_header);\n+ iov_out[0].iov_base = &out_header;\n+ iov_out[1].iov_len = sizeof(out_payload);\n+ iov_out[1].iov_base = &out_payload;\n+\n+ SetExpected(iov_in, 2, iov_out, 2);\n+\n+ struct stat stat_buf;\n+ EXPECT_THAT(stat(mount_point_.path().c_str(), &stat_buf), SyscallSucceeds());\n+\n+ struct stat expected_stat = {\n+ .st_ino = attr.ino,\n+ .st_nlink = attr.nlink,\n+ .st_mode = expected_mode,\n+ .st_uid = attr.uid,\n+ .st_gid = attr.gid,\n+ .st_rdev = attr.rdev,\n+ .st_size = static_cast<off_t>(attr.size),\n+ .st_blksize = attr.blksize,\n+ .st_blocks = static_cast<blkcnt_t>(attr.blocks),\n+ .st_atim = atime,\n+ .st_mtim = mtime,\n+ .st_ctim = ctime,\n+ };\n+ EXPECT_TRUE(StatsAreEqual(stat_buf, expected_stat));\n+ WaitCompleted();\n+}\n+\n+TEST_F(StatTest, StatNotFound) {\n+ struct iovec iov_in[2];\n+ struct iovec iov_out[2];\n+\n+ struct fuse_in_header in_header = {\n+ .len = sizeof(struct fuse_in_header) + sizeof(struct fuse_getattr_in),\n+ .opcode = FUSE_GETATTR,\n+ .unique = 4,\n+ };\n+ struct fuse_getattr_in in_payload = {0};\n+ iov_in[0].iov_len = sizeof(in_header);\n+ iov_in[0].iov_base = &in_header;\n+ iov_in[1].iov_len = sizeof(in_payload);\n+ iov_in[1].iov_base = &in_payload;\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header),\n+ .error = -ENOENT,\n+ .unique = 4,\n+ };\n+ iov_out[0].iov_len = sizeof(out_header);\n+ iov_out[0].iov_base = &out_header;\n+\n+ SetExpected(iov_in, 2, iov_out, 1);\n+\n+ struct stat stat_buf;\n+ EXPECT_THAT(stat(mount_point_.path().c_str(), &stat_buf),\n+ SyscallFailsWithErrno(ENOENT));\n+ WaitCompleted();\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runner/defs.bzl",
"new_path": "test/runner/defs.bzl",
"diff": "@@ -150,31 +150,12 @@ def syscall_test(\nif not tags:\ntags = []\n- _syscall_test(\n- test = test,\n- shard_count = shard_count,\n- size = size,\n- platform = \"native\",\n- use_tmpfs = False,\n- add_uds_tree = add_uds_tree,\n- tags = list(tags),\n- )\n-\n- for (platform, platform_tags) in platforms.items():\n- _syscall_test(\n- test = test,\n- shard_count = shard_count,\n- size = size,\n- platform = platform,\n- use_tmpfs = use_tmpfs,\n- add_uds_tree = add_uds_tree,\n- tags = platform_tags + tags,\n- )\n-\nvfs2_tags = list(tags)\nif vfs2:\n# Add tag to easily run VFS2 tests with --test_tag_filters=vfs2\nvfs2_tags.append(\"vfs2\")\n+ if fuse:\n+ vfs2_tags.append(\"fuse\")\nelse:\n# Don't automatically run tests tests not yet passing.\n@@ -191,19 +172,31 @@ def syscall_test(\nadd_uds_tree = add_uds_tree,\ntags = platforms[default_platform] + vfs2_tags,\nvfs2 = True,\n+ fuse = fuse,\n)\n+ if fuse:\n+ # Only generate *_vfs2_fuse target if fuse parameter is enabled.\n+ return\n- if vfs2 and fuse:\n_syscall_test(\ntest = test,\nshard_count = shard_count,\nsize = size,\n- platform = default_platform,\n+ platform = \"native\",\n+ use_tmpfs = False,\n+ add_uds_tree = add_uds_tree,\n+ tags = list(tags),\n+ )\n+\n+ for (platform, platform_tags) in platforms.items():\n+ _syscall_test(\n+ test = test,\n+ shard_count = shard_count,\n+ size = size,\n+ platform = platform,\nuse_tmpfs = use_tmpfs,\nadd_uds_tree = add_uds_tree,\n- tags = platforms[default_platform] + vfs2_tags + [\"fuse\"],\n- vfs2 = True,\n- fuse = True,\n+ tags = platform_tags + tags,\n)\n# TODO(gvisor.dev/issue/1487): Enable VFS2 overlay tests.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement FUSE_GETATTR
FUSE_GETATTR is called when a stat(2), fstat(2), or lstat(2) is issued
from VFS2 layer to a FUSE filesystem.
Fixes #3175 |
259,891 | 10.08.2020 19:32:48 | 25,200 | 8e31f0dc57d44fb463441f6156fba5c240369dfe | Set the NetworkProtocolNumber of all PacketBuffers.
NetworkEndpoints set the number on outgoing packets in Write() and
NetworkProtocols set them on incoming packets in Parse().
Needed for | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -176,6 +176,7 @@ func (e *endpoint) writePacketFragments(r *stack.Route, gso *stack.GSO, mtu int,\nHeader: pkt.Header,\nData: newPayload,\nNetworkHeader: buffer.View(h),\n+ NetworkProtocolNumber: header.IPv4ProtocolNumber,\n}); err != nil {\nreturn err\n}\n@@ -195,6 +196,7 @@ func (e *endpoint) writePacketFragments(r *stack.Route, gso *stack.GSO, mtu int,\nHeader: pkt.Header,\nData: newPayload,\nNetworkHeader: buffer.View(h),\n+ NetworkProtocolNumber: header.IPv4ProtocolNumber,\n}); err != nil {\nreturn err\n}\n@@ -209,6 +211,7 @@ func (e *endpoint) writePacketFragments(r *stack.Route, gso *stack.GSO, mtu int,\nHeader: startOfHdr,\nData: emptyVV,\nNetworkHeader: buffer.View(h),\n+ NetworkProtocolNumber: header.IPv4ProtocolNumber,\n}); err != nil {\nreturn err\n}\n@@ -249,10 +252,11 @@ func (e *endpoint) addIPHeader(r *stack.Route, hdr *buffer.Prependable, payloadS\nfunc (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.NetworkHeaderParams, pkt *stack.PacketBuffer) *tcpip.Error {\nip := e.addIPHeader(r, &pkt.Header, pkt.Data.Size(), params)\npkt.NetworkHeader = buffer.View(ip)\n+ pkt.NetworkProtocolNumber = header.IPv4ProtocolNumber\n- nicName := e.stack.FindNICNameFromID(e.NICID())\n// iptables filtering. All packets that reach here are locally\n// generated.\n+ nicName := e.stack.FindNICNameFromID(e.NICID())\nipt := e.stack.IPTables()\nif ok := ipt.Check(stack.Output, pkt, gso, r, \"\", nicName); !ok {\n// iptables is telling us to drop the packet.\n@@ -304,6 +308,7 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts stack.Packe\nfor pkt := pkts.Front(); pkt != nil; {\nip := e.addIPHeader(r, &pkt.Header, pkt.Data.Size(), params)\npkt.NetworkHeader = buffer.View(ip)\n+ pkt.NetworkProtocolNumber = header.IPv4ProtocolNumber\npkt = pkt.Next()\n}\n@@ -570,6 +575,7 @@ func (*protocol) Parse(pkt *stack.PacketBuffer) (proto tcpip.TransportProtocolNu\nparseTransportHeader = false\n}\n+ pkt.NetworkProtocolNumber = header.IPv4ProtocolNumber\npkt.NetworkHeader = hdr\npkt.Data.TrimFront(len(hdr))\npkt.Data.CapLength(int(ipHdr.TotalLength()) - len(hdr))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"diff": "@@ -150,6 +150,9 @@ func compareFragments(t *testing.T, packets []*stack.PacketBuffer, sourcePacketI\nif got, want := packet.Header.AvailableLength(), sourcePacketInfo.Header.AvailableLength()-header.IPv4MinimumSize; got != want {\nt.Errorf(\"fragment #%d should have the same available space for prepending as source: got %d, want %d\", i, got, want)\n}\n+ if got, want := packet.NetworkProtocolNumber, sourcePacketInfo.NetworkProtocolNumber; got != want {\n+ t.Errorf(\"fragment #%d has wrong network protocol number: got %d, want %d\", i, got, want)\n+ }\nif i < len(packets)-1 {\nsourceCopy.SetFlagsFragmentOffset(sourceCopy.Flags()|header.IPv4FlagMoreFragments, offset)\n} else {\n@@ -286,6 +289,7 @@ func TestFragmentation(t *testing.T) {\nHeader: hdr,\n// Save the source payload because WritePacket will modify it.\nData: payload.Clone(nil),\n+ NetworkProtocolNumber: header.IPv4ProtocolNumber,\n}\nc := buildContext(t, nil, ft.mtu)\nerr := c.Route.WritePacket(ft.gso, stack.NetworkHeaderParams{\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -117,6 +117,7 @@ func (e *endpoint) addIPHeader(r *stack.Route, hdr *buffer.Prependable, payloadS\nfunc (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.NetworkHeaderParams, pkt *stack.PacketBuffer) *tcpip.Error {\nip := e.addIPHeader(r, &pkt.Header, pkt.Data.Size(), params)\npkt.NetworkHeader = buffer.View(ip)\n+ pkt.NetworkProtocolNumber = header.IPv6ProtocolNumber\nif r.Loop&stack.PacketLoop != 0 {\n// The inbound path expects the network header to still be in\n@@ -152,6 +153,7 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts stack.Packe\nfor pb := pkts.Front(); pb != nil; pb = pb.Next() {\nip := e.addIPHeader(r, &pb.Header, pb.Data.Size(), params)\npb.NetworkHeader = buffer.View(ip)\n+ pb.NetworkProtocolNumber = header.IPv6ProtocolNumber\n}\nn, err := e.linkEP.WritePackets(r, gso, pkts, ProtocolNumber)\n@@ -586,6 +588,7 @@ traverseExtensions:\n}\nipHdr = header.IPv6(hdr)\n+ pkt.NetworkProtocolNumber = header.IPv6ProtocolNumber\npkt.NetworkHeader = hdr\npkt.Data.TrimFront(len(hdr))\npkt.Data.CapLength(int(ipHdr.PayloadLength()))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/packet_buffer.go",
"new_path": "pkg/tcpip/stack/packet_buffer.go",
"diff": "@@ -62,6 +62,11 @@ type PacketBuffer struct {\nNetworkHeader buffer.View\nTransportHeader buffer.View\n+ // NetworkProtocol is only valid when NetworkHeader is set.\n+ // TODO(gvisor.dev/issue/3574): Remove the separately passed protocol\n+ // numbers in registration APIs that take a PacketBuffer.\n+ NetworkProtocolNumber tcpip.NetworkProtocolNumber\n+\n// Hash is the transport layer hash of this packet. A value of zero\n// indicates no valid hash has been set.\nHash uint32\n@@ -74,7 +79,6 @@ type PacketBuffer struct {\n// is added to a queue.\nEgressRoute *Route\nGSOOptions *GSO\n- NetworkProtocolNumber tcpip.NetworkProtocolNumber\n// NatDone indicates if the packet has been manipulated as per NAT\n// iptables rule.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/registration.go",
"new_path": "pkg/tcpip/stack/registration.go",
"diff": "@@ -249,8 +249,8 @@ type NetworkEndpoint interface {\nMaxHeaderLength() uint16\n// WritePacket writes a packet to the given destination address and\n- // protocol. It takes ownership of pkt. pkt.TransportHeader must have already\n- // been set.\n+ // protocol. It takes ownership of pkt. pkt.TransportHeader must have\n+ // already been set.\nWritePacket(r *Route, gso *GSO, params NetworkHeaderParams, pkt *PacketBuffer) *tcpip.Error\n// WritePackets writes packets to the given destination address and\n"
}
] | Go | Apache License 2.0 | google/gvisor | Set the NetworkProtocolNumber of all PacketBuffers.
NetworkEndpoints set the number on outgoing packets in Write() and
NetworkProtocols set them on incoming packets in Parse().
Needed for #3549.
PiperOrigin-RevId: 325938745 |
259,975 | 11.08.2020 10:35:46 | 25,200 | 89f3197fc368702cbe1842932d9cfbede250269f | Mark integration tests as passing in VFS2 except CheckpointRestore.
Mark all tests passing for VFS2 in:
image_test
integration_test
There's no way to do negative look ahead/behind in golang test regex,
so check if the tests uses VFS2 and skip CheckPointRestore if it does. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -166,15 +166,11 @@ do-tests: runsc\nsimple-tests: unit-tests # Compatibility target.\n.PHONY: simple-tests\n-# Keep these in sync with //scripts/docker_tests.sh.\n-IMAGE_FILTER := HelloWorld\\|Httpd\\|Ruby\\|Stdio\n-INTEGRATION_FILTER := Life\\|Pause\\|Connect\\|JobControl\\|Overlay\\|Exec\\|DirCreation\\|Link\n-\ndocker-tests: load-basic-images\n@$(call submake,install-test-runtime RUNTIME=\"vfs1\")\n@$(call submake,test-runtime RUNTIME=\"vfs1\" TARGETS=\"$(INTEGRATION_TARGETS)\")\n@$(call submake,install-test-runtime RUNTIME=\"vfs2\" ARGS=\"--vfs2\")\n- @$(call submake,test-runtime RUNTIME=\"vfs2\" OPTIONS=\"--test_filter=$(IMAGE_FILTER)\\|$(INTEGRATION_FILTER)\" TARGETS=\"$(INTEGRATION_TARGETS)\")\n+ @$(call submake,test-runtime RUNTIME=\"vfs2\" TARGETS=\"$(INTEGRATION_TARGETS)\")\n.PHONY: docker-tests\noverlay-tests: load-basic-images\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/test/dockerutil/dockerutil.go",
"new_path": "pkg/test/dockerutil/dockerutil.go",
"diff": "@@ -88,44 +88,74 @@ func EnsureSupportedDockerVersion() {\n// RuntimePath returns the binary path for the current runtime.\nfunc RuntimePath() (string, error) {\n+ rs, err := runtimeMap()\n+ if err != nil {\n+ return \"\", err\n+ }\n+\n+ p, ok := rs[\"path\"].(string)\n+ if !ok {\n+ // The runtime does not declare a path.\n+ return \"\", fmt.Errorf(\"runtime does not declare a path: %v\", rs)\n+ }\n+ return p, nil\n+}\n+\n+// UsingVFS2 returns true if the 'runtime' has the vfs2 flag set.\n+// TODO(gvisor.dev/issue/1624): Remove.\n+func UsingVFS2() (bool, error) {\n+ rMap, err := runtimeMap()\n+ if err != nil {\n+ return false, err\n+ }\n+\n+ list, ok := rMap[\"runtimeArgs\"].([]interface{})\n+ if !ok {\n+ return false, fmt.Errorf(\"unexpected format: %v\", rMap)\n+ }\n+\n+ for _, element := range list {\n+ if element == \"--vfs2\" {\n+ return true, nil\n+ }\n+ }\n+ return false, nil\n+}\n+\n+func runtimeMap() (map[string]interface{}, error) {\n// Read the configuration data; the file must exist.\nconfigBytes, err := ioutil.ReadFile(*config)\nif err != nil {\n- return \"\", err\n+ return nil, err\n}\n// Unmarshal the configuration.\nc := make(map[string]interface{})\nif err := json.Unmarshal(configBytes, &c); err != nil {\n- return \"\", err\n+ return nil, err\n}\n// Decode the expected configuration.\nr, ok := c[\"runtimes\"]\nif !ok {\n- return \"\", fmt.Errorf(\"no runtimes declared: %v\", c)\n+ return nil, fmt.Errorf(\"no runtimes declared: %v\", c)\n}\nrs, ok := r.(map[string]interface{})\nif !ok {\n// The runtimes are not a map.\n- return \"\", fmt.Errorf(\"unexpected format: %v\", c)\n+ return nil, fmt.Errorf(\"unexpected format: %v\", rs)\n}\nr, ok = rs[*runtime]\nif !ok {\n// The expected runtime is not declared.\n- return \"\", fmt.Errorf(\"runtime %q not found: %v\", *runtime, c)\n+ return nil, fmt.Errorf(\"runtime %q not found: %v\", *runtime, rs)\n}\nrs, ok = r.(map[string]interface{})\nif !ok {\n// The runtime is not a map.\n- return \"\", fmt.Errorf(\"unexpected format: %v\", c)\n+ return nil, fmt.Errorf(\"unexpected format: %v\", r)\n}\n- p, ok := rs[\"path\"].(string)\n- if !ok {\n- // The runtime does not declare a path.\n- return \"\", fmt.Errorf(\"unexpected format: %v\", c)\n- }\n- return p, nil\n+ return rs, nil\n}\n// Save exports a container image to the given Writer.\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/docker_tests.sh",
"new_path": "scripts/docker_tests.sh",
"diff": "@@ -22,7 +22,4 @@ install_runsc_for_test docker\ntest_runsc //test/image:image_test //test/e2e:integration_test\ninstall_runsc_for_test docker --vfs2\n-# Sync with //Makefile.\n-IMAGE_FILTER=\"Hello|Httpd|Ruby|Stdio\"\n-INTEGRATION_FILTER=\"LifeCycle|Pause|Connect|JobControl|Overlay|Exec|DirCreation|Link\"\n-test_runsc //test/e2e:integration_test //test/image:image_test --test_filter=\"${IMAGE_FILTER}|${INTEGRATION_FILTER}\"\n+test_runsc //test/e2e:integration_test //test/image:image_test\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/integration_test.go",
"new_path": "test/e2e/integration_test.go",
"diff": "@@ -167,6 +167,13 @@ func TestCheckpointRestore(t *testing.T) {\nt.Skip(\"Pause/resume is not supported.\")\n}\n+ // TODO(gvisor.dev/issue/3373): Remove after implementing.\n+ if usingVFS2, err := dockerutil.UsingVFS2(); usingVFS2 {\n+ t.Skip(\"CheckpointRestore not implemented in VFS2.\")\n+ } else if err != nil {\n+ t.Fatalf(\"failed to read config for runtime %s: %v\", dockerutil.Runtime(), err)\n+ }\n+\nctx := context.Background()\nd := dockerutil.MakeContainer(ctx, t)\ndefer d.CleanUp(ctx)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Mark integration tests as passing in VFS2 except CheckpointRestore.
Mark all tests passing for VFS2 in:
image_test
integration_test
There's no way to do negative look ahead/behind in golang test regex,
so check if the tests uses VFS2 and skip CheckPointRestore if it does.
PiperOrigin-RevId: 326050915 |
259,858 | 11.08.2020 16:48:22 | 25,200 | c92242c89a47e75cc8a0aa40bcb2b105ce795b90 | Fix-up issue comment. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/qdisc/fifo/endpoint.go",
"new_path": "pkg/tcpip/link/qdisc/fifo/endpoint.go",
"diff": "@@ -199,7 +199,7 @@ func (e *endpoint) WritePackets(_ *stack.Route, _ *stack.GSO, pkts stack.PacketB\n// WriteRawPacket implements stack.LinkEndpoint.WriteRawPacket.\nfunc (e *endpoint) WriteRawPacket(vv buffer.VectorisedView) *tcpip.Error {\n- // TODO(gvisor.dev/issue/3267/): Queue these packets as well once\n+ // TODO(gvisor.dev/issue/3267): Queue these packets as well once\n// WriteRawPacket takes PacketBuffer instead of VectorisedView.\nreturn e.lower.WriteRawPacket(vv)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix-up issue comment.
PiperOrigin-RevId: 326129258 |
259,992 | 12.08.2020 11:12:12 | 25,200 | 776c5f633edc993652bc8e95418729e0420c6324 | Fix race in vfs.FileDescription.statusFlag | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/file_description.go",
"new_path": "pkg/sentry/vfs/file_description.go",
"diff": "@@ -289,7 +289,7 @@ func (fd *FileDescription) SetStatusFlags(ctx context.Context, creds *auth.Crede\nif flags&linux.O_DIRECT != 0 && !fd.opts.AllowDirectIO {\nreturn syserror.EINVAL\n}\n- // TODO(jamieliu): FileDescriptionImpl.SetOAsync()?\n+ // TODO(gvisor.dev/issue/1035): FileDescriptionImpl.SetOAsync()?\nconst settableFlags = linux.O_APPEND | linux.O_ASYNC | linux.O_DIRECT | linux.O_NOATIME | linux.O_NONBLOCK\nfd.flagsMu.Lock()\nif fd.asyncHandler != nil {\n@@ -301,7 +301,7 @@ func (fd *FileDescription) SetStatusFlags(ctx context.Context, creds *auth.Crede\nfd.asyncHandler.Unregister(fd)\n}\n}\n- fd.statusFlags = (oldFlags &^ settableFlags) | (flags & settableFlags)\n+ atomic.StoreUint32(&fd.statusFlags, (oldFlags&^settableFlags)|(flags&settableFlags))\nfd.flagsMu.Unlock()\nreturn nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix race in vfs.FileDescription.statusFlag
PiperOrigin-RevId: 326270643 |
259,860 | 12.08.2020 13:03:14 | 25,200 | c5ed390162930b51719ff45956d7ac1bc963c8e7 | Release fd references on aio callback cancellation.
Discovered by reference leak checker on tmpfs.inode. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/aio.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/aio.go",
"diff": "@@ -144,6 +144,12 @@ func submitCallback(t *kernel.Task, id uint64, cb *linux.IOCallback, cbAddr user\nfunc getAIOCallback(t *kernel.Task, fd, eventFD *vfs.FileDescription, cbAddr usermem.Addr, cb *linux.IOCallback, ioseq usermem.IOSequence, aioCtx *mm.AIOContext) kernel.AIOCallback {\nreturn func(ctx context.Context) {\n+ // Release references after completing the callback.\n+ defer fd.DecRef(ctx)\n+ if eventFD != nil {\n+ defer eventFD.DecRef(ctx)\n+ }\n+\nif aioCtx.Dead() {\naioCtx.CancelPendingRequest()\nreturn\n@@ -169,8 +175,6 @@ func getAIOCallback(t *kernel.Task, fd, eventFD *vfs.FileDescription, cbAddr use\nev.Result = -int64(kernel.ExtractErrno(err, 0))\n}\n- fd.DecRef(ctx)\n-\n// Queue the result for delivery.\naioCtx.FinishRequest(ev)\n@@ -179,7 +183,6 @@ func getAIOCallback(t *kernel.Task, fd, eventFD *vfs.FileDescription, cbAddr use\n// wake up.\nif eventFD != nil {\neventFD.Impl().(*eventfd.EventFileDescription).Signal(1)\n- eventFD.DecRef(ctx)\n}\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Release fd references on aio callback cancellation.
Discovered by reference leak checker on tmpfs.inode.
PiperOrigin-RevId: 326294755 |
259,992 | 12.08.2020 13:12:05 | 25,200 | d797f2666629737920b39a2fbac369ce5853dc35 | Redirect TODO
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/host.go",
"new_path": "pkg/sentry/fsimpl/host/host.go",
"diff": "@@ -552,7 +552,7 @@ func (f *fileDescription) Allocate(ctx context.Context, mode, offset, length uin\nreturn syserror.ESPIPE\n}\n- // TODO(gvisor.dev/issue/2923): Implement Allocate for non-pipe hostfds.\n+ // TODO(gvisor.dev/issue/3589): Implement Allocate for non-pipe hostfds.\nreturn syserror.EOPNOTSUPP\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Redirect TODO
Fixes #2923
PiperOrigin-RevId: 326296589 |
259,891 | 12.08.2020 15:43:38 | 25,200 | d50f2e2c7639084bbccac35fcc5f55e3f83f646a | ip6tables: ABI structs and constants
Part of | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/BUILD",
"new_path": "pkg/abi/linux/BUILD",
"diff": "@@ -41,6 +41,7 @@ go_library(\n\"mm.go\",\n\"netdevice.go\",\n\"netfilter.go\",\n+ \"netfilter_ipv6.go\",\n\"netlink.go\",\n\"netlink_route.go\",\n\"poll.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/netfilter.go",
"new_path": "pkg/abi/linux/netfilter.go",
"diff": "@@ -412,7 +412,7 @@ func (ke *KernelIPTGetEntries) SizeBytes() int {\nfunc (ke *KernelIPTGetEntries) MarshalBytes(dst []byte) {\nke.IPTGetEntries.MarshalBytes(dst)\nmarshalledUntil := ke.IPTGetEntries.SizeBytes()\n- for i := 0; i < len(ke.Entrytable); i++ {\n+ for i := range ke.Entrytable {\nke.Entrytable[i].MarshalBytes(dst[marshalledUntil:])\nmarshalledUntil += ke.Entrytable[i].SizeBytes()\n}\n@@ -422,7 +422,7 @@ func (ke *KernelIPTGetEntries) MarshalBytes(dst []byte) {\nfunc (ke *KernelIPTGetEntries) UnmarshalBytes(src []byte) {\nke.IPTGetEntries.UnmarshalBytes(src)\nunmarshalledUntil := ke.IPTGetEntries.SizeBytes()\n- for i := 0; i < len(ke.Entrytable); i++ {\n+ for i := range ke.Entrytable {\nke.Entrytable[i].UnmarshalBytes(src[unmarshalledUntil:])\nunmarshalledUntil += ke.Entrytable[i].SizeBytes()\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/abi/linux/netfilter_ipv6.go",
"diff": "+// Copyright 2020 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+import (\n+ \"io\"\n+\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+ \"gvisor.dev/gvisor/tools/go_marshal/marshal\"\n+ \"gvisor.dev/gvisor/tools/go_marshal/primitive\"\n+)\n+\n+// This file contains structures required to support IPv6 netfilter and\n+// ip6tables. Some constants and structs are equal to their IPv4 analogues, and\n+// are only distinguished by context (e.g. whether used on an IPv4 of IPv6\n+// socket).\n+\n+// Socket options for SOL_SOCLET. These correspond to values in\n+// include/uapi/linux/netfilter_ipv6/ip6_tables.h.\n+const (\n+ IP6T_BASE_CTL = 64\n+ IP6T_SO_SET_REPLACE = IPT_BASE_CTL\n+ IP6T_SO_SET_ADD_COUNTERS = IPT_BASE_CTL + 1\n+ IP6T_SO_SET_MAX = IPT_SO_SET_ADD_COUNTERS\n+\n+ IP6T_SO_GET_INFO = IPT_BASE_CTL\n+ IP6T_SO_GET_ENTRIES = IPT_BASE_CTL + 1\n+ IP6T_SO_GET_REVISION_MATCH = IPT_BASE_CTL + 4\n+ IP6T_SO_GET_REVISION_TARGET = IPT_BASE_CTL + 5\n+ IP6T_SO_GET_MAX = IP6T_SO_GET_REVISION_TARGET\n+)\n+\n+// IP6T_ORIGINAL_DST is the ip6tables SOL_IPV6 socket option. Corresponds to\n+// the value in include/uapi/linux/netfilter_ipv6/ip6_tables.h.\n+// TODO(gvisor.dev/issue/3549): Support IPv6 original destination.\n+const IP6T_ORIGINAL_DST = 80\n+\n+// IP6TReplace is the argument for the IP6T_SO_SET_REPLACE sockopt. It\n+// corresponds to struct ip6t_replace in\n+// include/uapi/linux/netfilter_ipv6/ip6_tables.h.\n+//\n+// +marshal\n+type IP6TReplace struct {\n+ Name TableName\n+ ValidHooks uint32\n+ NumEntries uint32\n+ Size uint32\n+ HookEntry [NF_INET_NUMHOOKS]uint32\n+ Underflow [NF_INET_NUMHOOKS]uint32\n+ NumCounters uint32\n+ Counters uint64 // This is really a *XTCounters.\n+ // Entries is omitted here because it would cause IP6TReplace to be an\n+ // extra byte longer (see http://www.catb.org/esr/structure-packing/).\n+ // Entries [0]IP6TEntry\n+}\n+\n+// SizeOfIP6TReplace is the size of an IP6TReplace.\n+const SizeOfIP6TReplace = 96\n+\n+// KernelIP6TGetEntries is identical to IP6TGetEntries, but includes the\n+// Entrytable field. This has been manually made marshal.Marshallable since it\n+// is dynamically sized.\n+type KernelIP6TGetEntries struct {\n+ IPTGetEntries\n+ Entrytable []KernelIP6TEntry\n+}\n+\n+// SizeBytes implements marshal.Marshallable.SizeBytes.\n+func (ke *KernelIP6TGetEntries) SizeBytes() int {\n+ res := ke.IPTGetEntries.SizeBytes()\n+ for _, entry := range ke.Entrytable {\n+ res += entry.SizeBytes()\n+ }\n+ return res\n+}\n+\n+// MarshalBytes implements marshal.Marshallable.MarshalBytes.\n+func (ke *KernelIP6TGetEntries) MarshalBytes(dst []byte) {\n+ ke.IPTGetEntries.MarshalBytes(dst)\n+ marshalledUntil := ke.IPTGetEntries.SizeBytes()\n+ for i := range ke.Entrytable {\n+ ke.Entrytable[i].MarshalBytes(dst[marshalledUntil:])\n+ marshalledUntil += ke.Entrytable[i].SizeBytes()\n+ }\n+}\n+\n+// UnmarshalBytes implements marshal.Marshallable.UnmarshalBytes.\n+func (ke *KernelIP6TGetEntries) UnmarshalBytes(src []byte) {\n+ ke.IPTGetEntries.UnmarshalBytes(src)\n+ unmarshalledUntil := ke.IPTGetEntries.SizeBytes()\n+ for i := range ke.Entrytable {\n+ ke.Entrytable[i].UnmarshalBytes(src[unmarshalledUntil:])\n+ unmarshalledUntil += ke.Entrytable[i].SizeBytes()\n+ }\n+}\n+\n+// Packed implements marshal.Marshallable.Packed.\n+func (ke *KernelIP6TGetEntries) Packed() bool {\n+ // KernelIP6TGetEntries isn't packed because the ke.Entrytable contains\n+ // an indirection to the actual data we want to marshal (the slice data\n+ // pointer), and the memory for KernelIP6TGetEntries contains the slice\n+ // header which we don't want to marshal.\n+ return false\n+}\n+\n+// MarshalUnsafe implements marshal.Marshallable.MarshalUnsafe.\n+func (ke *KernelIP6TGetEntries) MarshalUnsafe(dst []byte) {\n+ // Fall back to safe Marshal because the type in not packed.\n+ ke.MarshalBytes(dst)\n+}\n+\n+// UnmarshalUnsafe implements marshal.Marshallable.UnmarshalUnsafe.\n+func (ke *KernelIP6TGetEntries) UnmarshalUnsafe(src []byte) {\n+ // Fall back to safe Unmarshal because the type in not packed.\n+ ke.UnmarshalBytes(src)\n+}\n+\n+// CopyIn implements marshal.Marshallable.CopyIn.\n+func (ke *KernelIP6TGetEntries) CopyIn(task marshal.Task, addr usermem.Addr) (int, error) {\n+ buf := task.CopyScratchBuffer(ke.SizeBytes()) // escapes: okay.\n+ length, err := task.CopyInBytes(addr, buf) // escapes: okay.\n+ // Unmarshal unconditionally. If we had a short copy-in, this results\n+ // in a partially unmarshalled struct.\n+ ke.UnmarshalBytes(buf) // escapes: fallback.\n+ return length, err\n+}\n+\n+// CopyOut implements marshal.Marshallable.CopyOut.\n+func (ke *KernelIP6TGetEntries) CopyOut(task marshal.Task, addr usermem.Addr) (int, error) {\n+ // Type KernelIP6TGetEntries doesn't have a packed layout in memory,\n+ // fall back to MarshalBytes.\n+ return task.CopyOutBytes(addr, ke.marshalAll(task))\n+}\n+\n+// CopyOutN implements marshal.Marshallable.CopyOutN.\n+func (ke *KernelIP6TGetEntries) CopyOutN(task marshal.Task, addr usermem.Addr, limit int) (int, error) {\n+ // Type KernelIP6TGetEntries doesn't have a packed layout in memory, fall\n+ // back to MarshalBytes.\n+ return task.CopyOutBytes(addr, ke.marshalAll(task)[:limit])\n+}\n+\n+func (ke *KernelIP6TGetEntries) marshalAll(task marshal.Task) []byte {\n+ buf := task.CopyScratchBuffer(ke.SizeBytes())\n+ ke.MarshalBytes(buf)\n+ return buf\n+}\n+\n+// WriteTo implements io.WriterTo.WriteTo.\n+func (ke *KernelIP6TGetEntries) WriteTo(w io.Writer) (int64, error) {\n+ buf := make([]byte, ke.SizeBytes())\n+ ke.MarshalBytes(buf)\n+ length, err := w.Write(buf)\n+ return int64(length), err\n+}\n+\n+var _ marshal.Marshallable = (*KernelIP6TGetEntries)(nil)\n+\n+// IP6TEntry is an iptables rule. It corresponds to struct ip6t_entry in\n+// include/uapi/linux/netfilter_ipv6/ip6_tables.h.\n+//\n+// +marshal\n+type IP6TEntry struct {\n+ // IPv6 is used to filter packets based on the IPv6 header.\n+ IPv6 IP6TIP\n+\n+ // NFCache relates to kernel-internal caching and isn't used by\n+ // userspace.\n+ NFCache uint32\n+\n+ // TargetOffset is the byte offset from the beginning of this IPTEntry\n+ // to the start of the entry's target.\n+ TargetOffset uint16\n+\n+ // NextOffset is the byte offset from the beginning of this IPTEntry to\n+ // the start of the next entry. It is thus also the size of the entry.\n+ NextOffset uint16\n+\n+ // Comeback is a return pointer. It is not used by userspace.\n+ Comeback uint32\n+\n+ _ [4]byte\n+\n+ // Counters holds the packet and byte counts for this rule.\n+ Counters XTCounters\n+\n+ // Elems holds the data for all this rule's matches followed by the\n+ // target. It is variable length -- users have to iterate over any\n+ // matches and use TargetOffset and NextOffset to make sense of the\n+ // data.\n+ //\n+ // Elems is omitted here because it would cause IPTEntry to be an extra\n+ // byte larger (see http://www.catb.org/esr/structure-packing/).\n+ //\n+ // Elems [0]byte\n+}\n+\n+// SizeOfIP6TEntry is the size of an IP6TEntry.\n+const SizeOfIP6TEntry = 168\n+\n+// KernelIP6TEntry is identical to IP6TEntry, but includes the Elems field.\n+// KernelIP6TEntry itself is not Marshallable but it implements some methods of\n+// marshal.Marshallable that help in other implementations of Marshallable.\n+type KernelIP6TEntry struct {\n+ Entry IP6TEntry\n+\n+ // Elems holds the data for all this rule's matches followed by the\n+ // target. It is variable length -- users have to iterate over any\n+ // matches and use TargetOffset and NextOffset to make sense of the\n+ // data.\n+ Elems primitive.ByteSlice\n+}\n+\n+// SizeBytes implements marshal.Marshallable.SizeBytes.\n+func (ke *KernelIP6TEntry) SizeBytes() int {\n+ return ke.Entry.SizeBytes() + ke.Elems.SizeBytes()\n+}\n+\n+// MarshalBytes implements marshal.Marshallable.MarshalBytes.\n+func (ke *KernelIP6TEntry) MarshalBytes(dst []byte) {\n+ ke.Entry.MarshalBytes(dst)\n+ ke.Elems.MarshalBytes(dst[ke.Entry.SizeBytes():])\n+}\n+\n+// UnmarshalBytes implements marshal.Marshallable.UnmarshalBytes.\n+func (ke *KernelIP6TEntry) UnmarshalBytes(src []byte) {\n+ ke.Entry.UnmarshalBytes(src)\n+ ke.Elems.UnmarshalBytes(src[ke.Entry.SizeBytes():])\n+}\n+\n+// IP6TIP contains information for matching a packet's IP header.\n+// It corresponds to struct ip6t_ip6 in\n+// include/uapi/linux/netfilter_ipv6/ip6_tables.h.\n+//\n+// +marshal\n+type IP6TIP struct {\n+ // Src is the source IP address.\n+ Src Inet6Addr\n+\n+ // Dst is the destination IP address.\n+ Dst Inet6Addr\n+\n+ // SrcMask is the source IP mask.\n+ SrcMask Inet6Addr\n+\n+ // DstMask is the destination IP mask.\n+ DstMask Inet6Addr\n+\n+ // InputInterface is the input network interface.\n+ InputInterface [IFNAMSIZ]byte\n+\n+ // OutputInterface is the output network interface.\n+ OutputInterface [IFNAMSIZ]byte\n+\n+ // InputInterfaceMask is the input interface mask.\n+ InputInterfaceMask [IFNAMSIZ]byte\n+\n+ // OuputInterfaceMask is the output interface mask.\n+ OutputInterfaceMask [IFNAMSIZ]byte\n+\n+ // Protocol is the transport protocol.\n+ Protocol uint16\n+\n+ // TOS matches TOS flags when Flags indicates filtering by TOS.\n+ TOS uint8\n+\n+ // Flags define matching behavior for the IP header.\n+ Flags uint8\n+\n+ // InverseFlags invert the meaning of fields in struct IPTIP. See the\n+ // IP6T_INV_* flags.\n+ InverseFlags uint8\n+\n+ // Linux defines in6_addr (Inet6Addr for us) as the union of a\n+ // 16-element byte array and a 4-element 32-bit integer array, so the\n+ // whole struct is 4-byte aligned.\n+ _ [3]byte\n+}\n+\n+const SizeOfIP6TIP = 136\n+\n+// Flags in IP6TIP.InverseFlags. Corresponding constants are in\n+// include/uapi/linux/netfilter_ipv6/ip6_tables.h.\n+const (\n+ // Invert the meaning of InputInterface.\n+ IP6T_INV_VIA_IN = 0x01\n+ // Invert the meaning of OutputInterface.\n+ IP6T_INV_VIA_OUT = 0x02\n+ // Invert the meaning of TOS.\n+ IP6T_INV_TOS = 0x04\n+ // Invert the meaning of Src.\n+ IP6T_INV_SRCIP = 0x08\n+ // Invert the meaning of Dst.\n+ IP6T_INV_DSTIP = 0x10\n+ // Invert the meaning of the IPT_F_FRAG flag.\n+ IP6T_INV_FRAG = 0x20\n+ // Enable all flags.\n+ IP6T_INV_MASK = 0x7F\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/netfilter_test.go",
"new_path": "pkg/abi/linux/netfilter_test.go",
"diff": "@@ -36,6 +36,9 @@ func TestSizes(t *testing.T) {\n{XTEntryTarget{}, SizeOfXTEntryTarget},\n{XTErrorTarget{}, SizeOfXTErrorTarget},\n{XTStandardTarget{}, SizeOfXTStandardTarget},\n+ {IP6TReplace{}, SizeOfIP6TReplace},\n+ {IP6TEntry{}, SizeOfIP6TEntry},\n+ {IP6TIP{}, SizeOfIP6TIP},\n}\nfor _, tc := range testCases {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/socket.go",
"new_path": "pkg/abi/linux/socket.go",
"diff": "@@ -259,6 +259,11 @@ type InetMulticastRequestWithNIC struct {\nInterfaceIndex int32\n}\n+// Inet6Addr is struct in6_addr, from uapi/linux/in6.h.\n+//\n+// +marshal\n+type Inet6Addr [16]byte\n+\n// SockAddrInet6 is struct sockaddr_in6, from uapi/linux/in6.h.\ntype SockAddrInet6 struct {\nFamily uint16\n"
}
] | Go | Apache License 2.0 | google/gvisor | ip6tables: ABI structs and constants
Part of #3549.
PiperOrigin-RevId: 326329028 |
259,907 | 12.08.2020 17:17:17 | 25,200 | 42b610d56750b4bb8e3d69b680e4fb538f8fb554 | [vfs2][gofer] Return appropriate errors when opening and creating files.
Fixes php test ext/standard/tests/file/touch_variation5.phpt on vfs2.
Updates
Also spotted a bug with O_EXCL, where we did not return EEXIST when we tried
to open the root of the filesystem with O_EXCL | O_CREAT.
Added some more tests for open() corner cases. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"new_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"diff": "@@ -844,6 +844,13 @@ func (fs *filesystem) OpenAt(ctx context.Context, rp *vfs.ResolvingPath, opts vf\n}\n}\nif rp.Done() {\n+ // Reject attempts to open mount root directory with O_CREAT.\n+ if mayCreate && rp.MustBeDir() {\n+ return nil, syserror.EISDIR\n+ }\n+ if mustCreate {\n+ return nil, syserror.EEXIST\n+ }\nreturn start.openLocked(ctx, rp, &opts)\n}\n@@ -856,6 +863,10 @@ afterTrailingSymlink:\nif err := parent.checkPermissions(rp.Credentials(), vfs.MayExec); err != nil {\nreturn nil, err\n}\n+ // Reject attempts to open directories with O_CREAT.\n+ if mayCreate && rp.MustBeDir() {\n+ return nil, syserror.EISDIR\n+ }\n// Determine whether or not we need to create a file.\nparent.dirMu.Lock()\nchild, err := fs.stepLocked(ctx, rp, parent, false /* mayFollowSymlinks */, &ds)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"diff": "@@ -320,7 +320,7 @@ func (fs *filesystem) OpenAt(ctx context.Context, rp *vfs.ResolvingPath, opts vf\nfs.mu.Lock()\ndefer fs.mu.Unlock()\nif rp.Done() {\n- // Reject attempts to open directories with O_CREAT.\n+ // Reject attempts to open mount root directory with O_CREAT.\nif rp.MustBeDir() {\nreturn nil, syserror.EISDIR\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/open.cc",
"new_path": "test/syscalls/linux/open.cc",
"diff": "@@ -95,6 +95,38 @@ TEST_F(OpenTest, OTruncAndReadOnlyFile) {\nOpen(dirpath.c_str(), O_TRUNC | O_RDONLY, 0666));\n}\n+TEST_F(OpenTest, OCreateDirectory) {\n+ SKIP_IF(IsRunningWithVFS1());\n+ auto dirpath = GetAbsoluteTestTmpdir();\n+\n+ // Normal case: existing directory.\n+ ASSERT_THAT(open(dirpath.c_str(), O_RDWR | O_CREAT, 0666),\n+ SyscallFailsWithErrno(EISDIR));\n+ // Trailing separator on existing directory.\n+ ASSERT_THAT(open(dirpath.append(\"/\").c_str(), O_RDWR | O_CREAT, 0666),\n+ SyscallFailsWithErrno(EISDIR));\n+ // Trailing separator on non-existing directory.\n+ ASSERT_THAT(open(JoinPath(dirpath, \"non-existent\").append(\"/\").c_str(),\n+ O_RDWR | O_CREAT, 0666),\n+ SyscallFailsWithErrno(EISDIR));\n+ // \".\" special case.\n+ ASSERT_THAT(open(JoinPath(dirpath, \".\").c_str(), O_RDWR | O_CREAT, 0666),\n+ SyscallFailsWithErrno(EISDIR));\n+}\n+\n+TEST_F(OpenTest, MustCreateExisting) {\n+ auto dirPath = GetAbsoluteTestTmpdir();\n+\n+ // Existing directory.\n+ ASSERT_THAT(open(dirPath.c_str(), O_RDWR | O_CREAT | O_EXCL, 0666),\n+ SyscallFailsWithErrno(EEXIST));\n+\n+ // Existing file.\n+ auto newFile = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(dirPath));\n+ ASSERT_THAT(open(newFile.path().c_str(), O_RDWR | O_CREAT | O_EXCL, 0666),\n+ SyscallFailsWithErrno(EEXIST));\n+}\n+\nTEST_F(OpenTest, ReadOnly) {\nchar buf;\nconst FileDescriptor ro_file =\n"
}
] | Go | Apache License 2.0 | google/gvisor | [vfs2][gofer] Return appropriate errors when opening and creating files.
Fixes php test ext/standard/tests/file/touch_variation5.phpt on vfs2.
Updates #3516
Also spotted a bug with O_EXCL, where we did not return EEXIST when we tried
to open the root of the filesystem with O_EXCL | O_CREAT.
Added some more tests for open() corner cases.
PiperOrigin-RevId: 326346863 |
259,860 | 12.08.2020 18:09:34 | 25,200 | 36134667b289a3e96e90abf9e18e1c2137069d6b | Add reference leak checking to vfs2 tmpfs.inode.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/refs_vfs2/refs_template.go",
"new_path": "pkg/refs_vfs2/refs_template.go",
"diff": "@@ -59,7 +59,7 @@ func (r *Refs) finalize() {\nnote = \"(Leak checker uninitialized): \"\n}\nif n := r.ReadRefs(); n != 0 {\n- log.Warningf(\"%sAtomicRefCount %p owned by %T garbage collected with ref count of %d (want 0)\", note, r, ownerType, n)\n+ log.Warningf(\"%sRefs %p owned by %T garbage collected with ref count of %d (want 0)\", note, r, ownerType, n)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/BUILD",
"new_path": "pkg/sentry/fsimpl/tmpfs/BUILD",
"diff": "@@ -26,6 +26,17 @@ go_template_instance(\n},\n)\n+go_template_instance(\n+ name = \"inode_refs\",\n+ out = \"inode_refs.go\",\n+ package = \"tmpfs\",\n+ prefix = \"inode\",\n+ template = \"//pkg/refs_vfs2:refs_template\",\n+ types = {\n+ \"T\": \"inode\",\n+ },\n+)\n+\ngo_library(\nname = \"tmpfs\",\nsrcs = [\n@@ -34,6 +45,7 @@ go_library(\n\"directory.go\",\n\"filesystem.go\",\n\"fstree.go\",\n+ \"inode_refs.go\",\n\"named_pipe.go\",\n\"regular_file.go\",\n\"socket_file.go\",\n@@ -47,6 +59,7 @@ go_library(\n\"//pkg/context\",\n\"//pkg/fspath\",\n\"//pkg/log\",\n+ \"//pkg/refs\",\n\"//pkg/safemem\",\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/fs\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"diff": "@@ -285,13 +285,10 @@ type inode struct {\n// fs is the owning filesystem. fs is immutable.\nfs *filesystem\n- // refs is a reference count. refs is accessed using atomic memory\n- // operations.\n- //\n// A reference is held on all inodes as long as they are reachable in the\n// filesystem tree, i.e. nlink is nonzero. This reference is dropped when\n// nlink reaches 0.\n- refs int64\n+ refs inodeRefs\n// xattrs implements extended attributes.\n//\n@@ -327,7 +324,6 @@ func (i *inode) init(impl interface{}, fs *filesystem, kuid auth.KUID, kgid auth\npanic(\"file type is required in FileMode\")\n}\ni.fs = fs\n- i.refs = 1\ni.mode = uint32(mode)\ni.uid = uint32(kuid)\ni.gid = uint32(kgid)\n@@ -339,6 +335,7 @@ func (i *inode) init(impl interface{}, fs *filesystem, kuid auth.KUID, kgid auth\ni.mtime = now\n// i.nlink initialized by caller\ni.impl = impl\n+ i.refs.EnableLeakCheck()\n}\n// incLinksLocked increments i's link count.\n@@ -369,25 +366,15 @@ func (i *inode) decLinksLocked(ctx context.Context) {\n}\nfunc (i *inode) incRef() {\n- if atomic.AddInt64(&i.refs, 1) <= 1 {\n- panic(\"tmpfs.inode.incRef() called without holding a reference\")\n- }\n+ i.refs.IncRef()\n}\nfunc (i *inode) tryIncRef() bool {\n- for {\n- refs := atomic.LoadInt64(&i.refs)\n- if refs == 0 {\n- return false\n- }\n- if atomic.CompareAndSwapInt64(&i.refs, refs, refs+1) {\n- return true\n- }\n- }\n+ return i.refs.TryIncRef()\n}\nfunc (i *inode) decRef(ctx context.Context) {\n- if refs := atomic.AddInt64(&i.refs, -1); refs == 0 {\n+ i.refs.DecRef(func() {\ni.watches.HandleDeletion(ctx)\nif regFile, ok := i.impl.(*regularFile); ok {\n// Release memory used by regFile to store data. Since regFile is\n@@ -395,9 +382,7 @@ func (i *inode) decRef(ctx context.Context) {\n// metadata.\nregFile.data.DropAll(regFile.memFile)\n}\n- } else if refs < 0 {\n- panic(\"tmpfs.inode.decRef() called without holding a reference\")\n- }\n+ })\n}\nfunc (i *inode) checkPermissions(creds *auth.Credentials, ats vfs.AccessTypes) error {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add reference leak checking to vfs2 tmpfs.inode.
Updates #1486.
PiperOrigin-RevId: 326354750 |
259,907 | 13.08.2020 16:56:39 | 25,200 | 5036f135e4370c84dd4afe1c43c14275b170c364 | Disable vfs2 for socket_stress_test. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -69,6 +69,7 @@ syscall_test(\n# involve much concurrency, TSAN's usefulness here is limited anyway.\ntags = [\"nogotsan\"],\ntest = \"//test/syscalls/linux:socket_stress_test\",\n+ vfs2 = False,\n)\nsyscall_test(\n"
}
] | Go | Apache License 2.0 | google/gvisor | Disable vfs2 for socket_stress_test.
PiperOrigin-RevId: 326553620 |
260,024 | 14.08.2020 02:05:23 | 25,200 | 190634e0fcf4cf25a449e1bd39533ca2ddad66e6 | Give the ICMP Code its own type
This is a preparatory commit for a larger commit working on
ICMP generation in error cases.
This is removal of technical debt and cleanup in the gvisor code
as part of gvisor issue 2211.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/checker/checker.go",
"new_path": "pkg/tcpip/checker/checker.go",
"diff": "@@ -699,7 +699,7 @@ func ICMPv4Type(want header.ICMPv4Type) TransportChecker {\n}\n// ICMPv4Code creates a checker that checks the ICMPv4 Code field.\n-func ICMPv4Code(want byte) TransportChecker {\n+func ICMPv4Code(want header.ICMPv4Code) TransportChecker {\nreturn func(t *testing.T, h header.Transport) {\nt.Helper()\n@@ -757,7 +757,7 @@ func ICMPv6Type(want header.ICMPv6Type) TransportChecker {\n}\n// ICMPv6Code creates a checker that checks the ICMPv6 Code field.\n-func ICMPv6Code(want byte) TransportChecker {\n+func ICMPv6Code(want header.ICMPv6Code) TransportChecker {\nreturn func(t *testing.T, h header.Transport) {\nt.Helper()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/icmpv4.go",
"new_path": "pkg/tcpip/header/icmpv4.go",
"diff": "@@ -54,6 +54,9 @@ const (\n// ICMPv4Type is the ICMP type field described in RFC 792.\ntype ICMPv4Type byte\n+// ICMPv4Code is the ICMP code field described in RFC 792.\n+type ICMPv4Code byte\n+\n// Typical values of ICMPv4Type defined in RFC 792.\nconst (\nICMPv4EchoReply ICMPv4Type = 0\n@@ -69,12 +72,13 @@ const (\nICMPv4InfoReply ICMPv4Type = 16\n)\n-// Values for ICMP code as defined in RFC 792.\n+// ICMP codes for ICMPv4 Destination Unreachable messages as defined in RFC 792.\nconst (\n- ICMPv4TTLExceeded = 0\n- ICMPv4HostUnreachable = 1\n- ICMPv4PortUnreachable = 3\n- ICMPv4FragmentationNeeded = 4\n+ ICMPv4TTLExceeded ICMPv4Code = 0\n+ ICMPv4HostUnreachable ICMPv4Code = 1\n+ ICMPv4ProtoUnreachable ICMPv4Code = 2\n+ ICMPv4PortUnreachable ICMPv4Code = 3\n+ ICMPv4FragmentationNeeded ICMPv4Code = 4\n)\n// Type is the ICMP type field.\n@@ -84,10 +88,10 @@ func (b ICMPv4) Type() ICMPv4Type { return ICMPv4Type(b[0]) }\nfunc (b ICMPv4) SetType(t ICMPv4Type) { b[0] = byte(t) }\n// Code is the ICMP code field. Its meaning depends on the value of Type.\n-func (b ICMPv4) Code() byte { return b[1] }\n+func (b ICMPv4) Code() ICMPv4Code { return ICMPv4Code(b[1]) }\n// SetCode sets the ICMP code field.\n-func (b ICMPv4) SetCode(c byte) { b[1] = c }\n+func (b ICMPv4) SetCode(c ICMPv4Code) { b[1] = byte(c) }\n// Checksum is the ICMP checksum field.\nfunc (b ICMPv4) Checksum() uint16 {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/icmpv6.go",
"new_path": "pkg/tcpip/header/icmpv6.go",
"diff": "@@ -92,7 +92,6 @@ const (\n// ICMPv6Type is the ICMP type field described in RFC 4443 and friends.\ntype ICMPv6Type byte\n-// Typical values of ICMPv6Type defined in RFC 4443.\nconst (\nICMPv6DstUnreachable ICMPv6Type = 1\nICMPv6PacketTooBig ICMPv6Type = 2\n@@ -110,18 +109,38 @@ const (\nICMPv6RedirectMsg ICMPv6Type = 137\n)\n-// Values for ICMP destination unreachable code as defined in RFC 4443 section\n-// 3.1.\n+// ICMPv6Code is the ICMP code field described in RFC 4443.\n+type ICMPv6Code byte\n+\n+// ICMP codes used with Destination Unreachable (Type 1). As per RFC 4443\n+// section 3.1.\n+const (\n+ ICMPv6NetworkUnreachable ICMPv6Code = 0\n+ ICMPv6Prohibited ICMPv6Code = 1\n+ ICMPv6BeyondScope ICMPv6Code = 2\n+ ICMPv6AddressUnreachable ICMPv6Code = 3\n+ ICMPv6PortUnreachable ICMPv6Code = 4\n+ ICMPv6Policy ICMPv6Code = 5\n+ ICMPv6RejectRoute ICMPv6Code = 6\n+)\n+\n+// ICMP codes used with Time Exceeded (Type 3). As per RFC 4443 section 3.3.\nconst (\n- ICMPv6NetworkUnreachable = 0\n- ICMPv6Prohibited = 1\n- ICMPv6BeyondScope = 2\n- ICMPv6AddressUnreachable = 3\n- ICMPv6PortUnreachable = 4\n- ICMPv6Policy = 5\n- ICMPv6RejectRoute = 6\n+ ICMPv6HopLimitExceeded ICMPv6Code = 0\n+ ICMPv6ReassemblyTimeout ICMPv6Code = 1\n)\n+// ICMP codes used with Parameter Problem (Type 4). As per RFC 4443 section 3.4.\n+const (\n+ ICMPv6ErroneousHeader ICMPv6Code = 0\n+ ICMPv6UnknownHeader ICMPv6Code = 1\n+ ICMPv6UnknownOption ICMPv6Code = 2\n+)\n+\n+// ICMPv6UnusedCode is the code value used with ICMPv6 messages which don't use\n+// the code field. (Types not mentioned above.)\n+const ICMPv6UnusedCode ICMPv6Code = 0\n+\n// Type is the ICMP type field.\nfunc (b ICMPv6) Type() ICMPv6Type { return ICMPv6Type(b[0]) }\n@@ -129,10 +148,10 @@ func (b ICMPv6) Type() ICMPv6Type { return ICMPv6Type(b[0]) }\nfunc (b ICMPv6) SetType(t ICMPv6Type) { b[0] = byte(t) }\n// Code is the ICMP code field. Its meaning depends on the value of Type.\n-func (b ICMPv6) Code() byte { return b[1] }\n+func (b ICMPv6) Code() ICMPv6Code { return ICMPv6Code(b[1]) }\n// SetCode sets the ICMP code field.\n-func (b ICMPv6) SetCode(c byte) { b[1] = c }\n+func (b ICMPv6) SetCode(c ICMPv6Code) { b[1] = byte(c) }\n// Checksum is the ICMP checksum field.\nfunc (b ICMPv6) Checksum() uint16 {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ip_test.go",
"new_path": "pkg/tcpip/network/ip_test.go",
"diff": "@@ -321,7 +321,7 @@ func TestIPv4ReceiveControl(t *testing.T) {\nname string\nexpectedCount int\nfragmentOffset uint16\n- code uint8\n+ code header.ICMPv4Code\nexpectedTyp stack.ControlType\nexpectedExtra uint32\ntrunc int\n@@ -579,7 +579,7 @@ func TestIPv6ReceiveControl(t *testing.T) {\nexpectedCount int\nfragmentOffset *uint16\ntyp header.ICMPv6Type\n- code uint8\n+ code header.ICMPv6Code\nexpectedTyp stack.ControlType\nexpectedExtra uint32\ntrunc int\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ndp_test.go",
"new_path": "pkg/tcpip/network/ipv6/ndp_test.go",
"diff": "@@ -637,7 +637,7 @@ func TestNDPValidation(t *testing.T) {\nname string\natomicFragment bool\nhopLimit uint8\n- code uint8\n+ code header.ICMPv6Code\nvalid bool\n}{\n{\n@@ -730,7 +730,7 @@ func TestRouterAdvertValidation(t *testing.T) {\nname string\nsrc tcpip.Address\nhopLimit uint8\n- code uint8\n+ code header.ICMPv6Code\nndpPayload []byte\nexpectedSuccess bool\n}{\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/testing/context/context.go",
"new_path": "pkg/tcpip/transport/tcp/testing/context/context.go",
"diff": "@@ -292,7 +292,7 @@ func (c *Context) GetPacketNonBlocking() []byte {\n}\n// SendICMPPacket builds and sends an ICMPv4 packet via the link layer endpoint.\n-func (c *Context) SendICMPPacket(typ header.ICMPv4Type, code uint8, p1, p2 []byte, maxTotalSize int) {\n+func (c *Context) SendICMPPacket(typ header.ICMPv4Type, code header.ICMPv4Code, p1, p2 []byte, maxTotalSize int) {\n// Allocate a buffer data and headers.\nbuf := buffer.NewView(header.IPv4MinimumSize + header.ICMPv4PayloadOffset + len(p2))\nif len(buf) > maxTotalSize {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/layers.go",
"new_path": "test/packetimpact/testbench/layers.go",
"diff": "@@ -775,7 +775,7 @@ func (l *IPv6FragmentExtHdr) String() string {\ntype ICMPv6 struct {\nLayerBase\nType *header.ICMPv6Type\n- Code *byte\n+ Code *header.ICMPv6Code\nChecksum *uint16\nPayload []byte\n}\n@@ -823,6 +823,12 @@ func ICMPv6Type(v header.ICMPv6Type) *header.ICMPv6Type {\nreturn &v\n}\n+// ICMPv6Code is a helper routine that allocates a new ICMPv6Type value to store\n+// v and returns a pointer to it.\n+func ICMPv6Code(v header.ICMPv6Code) *header.ICMPv6Code {\n+ return &v\n+}\n+\n// Byte is a helper routine that allocates a new byte value to store\n// v and returns a pointer to it.\nfunc Byte(v byte) *byte {\n@@ -834,7 +840,7 @@ func parseICMPv6(b []byte) (Layer, layerParser) {\nh := header.ICMPv6(b)\nicmpv6 := ICMPv6{\nType: ICMPv6Type(h.Type()),\n- Code: Byte(h.Code()),\n+ Code: ICMPv6Code(h.Code()),\nChecksum: Uint16(h.Checksum()),\nPayload: h.NDPPayload(),\n}\n@@ -861,11 +867,17 @@ func ICMPv4Type(t header.ICMPv4Type) *header.ICMPv4Type {\nreturn &t\n}\n+// ICMPv4Code is a helper routine that allocates a new header.ICMPv4Code value\n+// to store t and returns a pointer to it.\n+func ICMPv4Code(t header.ICMPv4Code) *header.ICMPv4Code {\n+ return &t\n+}\n+\n// ICMPv4 can construct and match an ICMPv4 encapsulation.\ntype ICMPv4 struct {\nLayerBase\nType *header.ICMPv4Type\n- Code *uint8\n+ Code *header.ICMPv4Code\nChecksum *uint16\n}\n@@ -881,7 +893,7 @@ func (l *ICMPv4) ToBytes() ([]byte, error) {\nh.SetType(*l.Type)\n}\nif l.Code != nil {\n- h.SetCode(byte(*l.Code))\n+ h.SetCode(*l.Code)\n}\nif l.Checksum != nil {\nh.SetChecksum(*l.Checksum)\n@@ -901,7 +913,7 @@ func parseICMPv4(b []byte) (Layer, layerParser) {\nh := header.ICMPv4(b)\nicmpv4 := ICMPv4{\nType: ICMPv4Type(h.Type()),\n- Code: Uint8(h.Code()),\n+ Code: ICMPv4Code(h.Code()),\nChecksum: Uint16(h.Checksum()),\n}\nreturn &icmpv4, parsePayload\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/layers_test.go",
"new_path": "test/packetimpact/testbench/layers_test.go",
"diff": "@@ -594,7 +594,7 @@ func TestIPv6ExtHdrOptions(t *testing.T) {\n},\n&ICMPv6{\nType: ICMPv6Type(header.ICMPv6ParamProblem),\n- Code: Byte(0),\n+ Code: ICMPv6Code(header.ICMPv6ErroneousHeader),\nChecksum: Uint16(0x5f98),\nPayload: []byte{0x00, 0x00, 0x00, 0x06},\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/ipv6_fragment_reassembly_test.go",
"new_path": "test/packetimpact/tests/ipv6_fragment_reassembly_test.go",
"diff": "@@ -67,7 +67,7 @@ func TestIPv6FragmentReassembly(t *testing.T) {\nrIP := tcpip.Address(net.ParseIP(testbench.RemoteIPv6).To16())\nicmpv6 := testbench.ICMPv6{\nType: testbench.ICMPv6Type(header.ICMPv6EchoRequest),\n- Code: testbench.Byte(0),\n+ Code: testbench.ICMPv6Code(header.ICMPv6UnusedCode),\nPayload: icmpv6EchoPayload,\n}\nicmpv6Bytes, err := icmpv6.ToBytes()\n@@ -89,7 +89,7 @@ func TestIPv6FragmentReassembly(t *testing.T) {\n},\n&testbench.ICMPv6{\nType: testbench.ICMPv6Type(header.ICMPv6EchoRequest),\n- Code: testbench.Byte(0),\n+ Code: testbench.ICMPv6Code(header.ICMPv6UnusedCode),\nPayload: icmpv6EchoPayload,\nChecksum: &cksum,\n})\n@@ -116,7 +116,7 @@ func TestIPv6FragmentReassembly(t *testing.T) {\n},\n&testbench.ICMPv6{\nType: testbench.ICMPv6Type(header.ICMPv6EchoReply),\n- Code: testbench.Byte(0),\n+ Code: testbench.ICMPv6Code(header.ICMPv6UnusedCode),\n},\n}, time.Second)\nif err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/ipv6_unknown_options_action_test.go",
"new_path": "test/packetimpact/tests/ipv6_unknown_options_action_test.go",
"diff": "@@ -172,7 +172,7 @@ func TestIPv6UnknownOptionAction(t *testing.T) {\n&testbench.IPv6{},\n&testbench.ICMPv6{\nType: testbench.ICMPv6Type(header.ICMPv6ParamProblem),\n- Code: testbench.Byte(2),\n+ Code: testbench.ICMPv6Code(header.ICMPv6UnknownOption),\nPayload: icmpv6Payload,\n},\n}, time.Second)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/tcp_network_unreachable_test.go",
"new_path": "test/packetimpact/tests/tcp_network_unreachable_test.go",
"diff": "@@ -72,7 +72,9 @@ func TestTCPSynSentUnreachable(t *testing.T) {\nif !ok {\nt.Fatalf(\"expected %s to be TCP\", tcpLayers[tcpLayer])\n}\n- var icmpv4 testbench.ICMPv4 = testbench.ICMPv4{Type: testbench.ICMPv4Type(header.ICMPv4DstUnreachable), Code: testbench.Uint8(header.ICMPv4HostUnreachable)}\n+ var icmpv4 testbench.ICMPv4 = testbench.ICMPv4{\n+ Type: testbench.ICMPv4Type(header.ICMPv4DstUnreachable),\n+ Code: testbench.ICMPv4Code(header.ICMPv4HostUnreachable)}\nlayers = append(layers, &icmpv4, ip, tcp)\nrawConn.SendFrameStateless(t, layers)\n@@ -126,7 +128,7 @@ func TestTCPSynSentUnreachable6(t *testing.T) {\n}\nvar icmpv6 testbench.ICMPv6 = testbench.ICMPv6{\nType: testbench.ICMPv6Type(header.ICMPv6DstUnreachable),\n- Code: testbench.Uint8(header.ICMPv6NetworkUnreachable),\n+ Code: testbench.ICMPv6Code(header.ICMPv6NetworkUnreachable),\n// Per RFC 4443 3.1, the payload contains 4 zeroed bytes.\nPayload: []byte{0, 0, 0, 0},\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/udp_icmp_error_propagation_test.go",
"new_path": "test/packetimpact/tests/udp_icmp_error_propagation_test.go",
"diff": "@@ -62,9 +62,13 @@ func (e icmpError) String() string {\nfunc (e icmpError) ToICMPv4() *testbench.ICMPv4 {\nswitch e {\ncase portUnreachable:\n- return &testbench.ICMPv4{Type: testbench.ICMPv4Type(header.ICMPv4DstUnreachable), Code: testbench.Uint8(header.ICMPv4PortUnreachable)}\n+ return &testbench.ICMPv4{\n+ Type: testbench.ICMPv4Type(header.ICMPv4DstUnreachable),\n+ Code: testbench.ICMPv4Code(header.ICMPv4PortUnreachable)}\ncase timeToLiveExceeded:\n- return &testbench.ICMPv4{Type: testbench.ICMPv4Type(header.ICMPv4TimeExceeded), Code: testbench.Uint8(header.ICMPv4TTLExceeded)}\n+ return &testbench.ICMPv4{\n+ Type: testbench.ICMPv4Type(header.ICMPv4TimeExceeded),\n+ Code: testbench.ICMPv4Code(header.ICMPv4TTLExceeded)}\n}\nreturn nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Give the ICMP Code its own type
This is a preparatory commit for a larger commit working on
ICMP generation in error cases.
This is removal of technical debt and cleanup in the gvisor code
as part of gvisor issue 2211.
Updates #2211.
PiperOrigin-RevId: 326615389 |
259,975 | 14.08.2020 10:51:12 | 25,200 | e6ea59203ba6e9c0431999463795a2c14036053f | Skip UDPMulticast Tests when net interfaces aren't found. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ipv4_udp_unbound_external_networking.cc",
"new_path": "test/syscalls/linux/socket_ipv4_udp_unbound_external_networking.cc",
"diff": "@@ -42,7 +42,9 @@ TestAddress V4EmptyAddress() {\n}\nvoid IPv4UDPUnboundExternalNetworkingSocketTest::SetUp() {\n- got_if_infos_ = false;\n+ // FIXME(b/137899561): Linux instance for syscall tests sometimes misses its\n+ // IPv4 address on eth0.\n+ found_net_interfaces_ = false;\n// Get interface list.\nASSERT_NO_ERRNO(if_helper_.Load());\n@@ -71,7 +73,7 @@ void IPv4UDPUnboundExternalNetworkingSocketTest::SetUp() {\n}\neth_if_addr_ = *reinterpret_cast<const sockaddr_in*>(eth_if_addr);\n- got_if_infos_ = true;\n+ found_net_interfaces_ = true;\n}\n// Verifies that a newly instantiated UDP socket does not have the\n@@ -110,6 +112,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest, SetUDPBroadcast) {\n// the destination port number.\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nUDPBroadcastReceivedOnExpectedPort) {\n+ SKIP_IF(!found_net_interfaces_);\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nauto rcvr1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nauto rcvr2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n@@ -185,9 +188,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// not a unicast address.\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nUDPBroadcastReceivedOnExpectedAddresses) {\n- // FIXME(b/137899561): Linux instance for syscall tests sometimes misses its\n- // IPv4 address on eth0.\n- SKIP_IF(!got_if_infos_);\n+ SKIP_IF(!found_net_interfaces_);\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nauto rcvr1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n@@ -272,6 +273,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// (UDPBroadcastSendRecvOnSocketBoundToAny).\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nUDPBroadcastSendRecvOnSocketBoundToBroadcast) {\n+ SKIP_IF(!found_net_interfaces_);\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n// Enable SO_BROADCAST.\n@@ -313,6 +315,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// (UDPBroadcastSendRecvOnSocketBoundToBroadcast).\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nUDPBroadcastSendRecvOnSocketBoundToAny) {\n+ SKIP_IF(!found_net_interfaces_);\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n// Enable SO_BROADCAST.\n@@ -351,6 +354,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// Verifies that a UDP broadcast fails to send on a socket with SO_BROADCAST\n// disabled.\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest, TestSendBroadcast) {\n+ SKIP_IF(!found_net_interfaces_);\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n// Broadcast a test message without having enabled SO_BROADCAST on the sending\n@@ -401,6 +405,8 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// multicast on gVisor.\nSKIP_IF(IsRunningOnGvisor());\n+ SKIP_IF(!found_net_interfaces_);\n+\nauto socket = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nauto bind_addr = V4Any();\n@@ -435,6 +441,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// Check that multicast packets will be delivered to the sending socket without\n// setting an interface.\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest, TestSendMulticastSelf) {\n+ SKIP_IF(!found_net_interfaces_);\nauto socket = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nauto bind_addr = V4Any();\n@@ -478,6 +485,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest, TestSendMulticastSelf) {\n// set interface and IP_MULTICAST_LOOP disabled.\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nTestSendMulticastSelfLoopOff) {\n+ SKIP_IF(!found_net_interfaces_);\nauto socket = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nauto bind_addr = V4Any();\n@@ -528,6 +536,8 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest, TestSendMulticastNoGroup) {\n// multicast on gVisor.\nSKIP_IF(IsRunningOnGvisor());\n+ SKIP_IF(!found_net_interfaces_);\n+\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nauto receiver = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n@@ -566,6 +576,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest, TestSendMulticastNoGroup) {\n// Check that multicast packets will be delivered to another socket without\n// setting an interface.\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest, TestSendMulticast) {\n+ SKIP_IF(!found_net_interfaces_);\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nauto receiver = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n@@ -613,6 +624,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest, TestSendMulticast) {\n// set interface and IP_MULTICAST_LOOP disabled on the sending socket.\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nTestSendMulticastSenderNoLoop) {\n+ SKIP_IF(!found_net_interfaces_);\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nauto receiver = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n@@ -664,6 +676,8 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// setting an interface and IP_MULTICAST_LOOP disabled on the receiving socket.\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nTestSendMulticastReceiverNoLoop) {\n+ SKIP_IF(!found_net_interfaces_);\n+\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nauto receiver = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n@@ -716,6 +730,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// and both will receive data on it when bound to the ANY address.\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nTestSendMulticastToTwoBoundToAny) {\n+ SKIP_IF(!found_net_interfaces_);\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nstd::unique_ptr<FileDescriptor> receivers[2] = {\nASSERT_NO_ERRNO_AND_VALUE(NewSocket()),\n@@ -782,6 +797,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// and both will receive data on it when bound to the multicast address.\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nTestSendMulticastToTwoBoundToMulticastAddress) {\n+ SKIP_IF(!found_net_interfaces_);\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nstd::unique_ptr<FileDescriptor> receivers[2] = {\nASSERT_NO_ERRNO_AND_VALUE(NewSocket()),\n@@ -851,6 +867,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// multicast address, both will receive data.\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nTestSendMulticastToTwoBoundToAnyAndMulticastAddress) {\n+ SKIP_IF(!found_net_interfaces_);\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nstd::unique_ptr<FileDescriptor> receivers[2] = {\nASSERT_NO_ERRNO_AND_VALUE(NewSocket()),\n@@ -924,6 +941,8 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// is not a multicast address.\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nIpMulticastLoopbackFromAddr) {\n+ SKIP_IF(!found_net_interfaces_);\n+\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nauto receiver = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n@@ -991,9 +1010,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// interface, a multicast packet sent out uses the latter as its source address.\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nIpMulticastLoopbackIfNicAndAddr) {\n- // FIXME(b/137899561): Linux instance for syscall tests sometimes misses its\n- // IPv4 address on eth0.\n- SKIP_IF(!got_if_infos_);\n+ SKIP_IF(!found_net_interfaces_);\n// Create receiver, bind to ANY and join the multicast group.\nauto receiver = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n@@ -1059,9 +1076,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// another interface.\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nIpMulticastLoopbackBindToOneIfSetMcastIfToAnother) {\n- // FIXME(b/137899561): Linux instance for syscall tests sometimes misses its\n- // IPv4 address on eth0.\n- SKIP_IF(!got_if_infos_);\n+ SKIP_IF(!found_net_interfaces_);\n// FIXME (b/137790511): When bound to one interface it is not possible to set\n// IP_MULTICAST_IF to a different interface.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ipv4_udp_unbound_external_networking.h",
"new_path": "test/syscalls/linux/socket_ipv4_udp_unbound_external_networking.h",
"diff": "@@ -29,9 +29,9 @@ class IPv4UDPUnboundExternalNetworkingSocketTest : public SimpleSocketTest {\nIfAddrHelper if_helper_;\n- // got_if_infos_ is set to false if SetUp() could not obtain all interface\n- // infos that we need.\n- bool got_if_infos_;\n+ // found_net_interfaces_ is set to false if SetUp() could not obtain\n+ // all interface infos that we need.\n+ bool found_net_interfaces_;\n// Interface infos.\nint lo_if_idx_;\n"
}
] | Go | Apache License 2.0 | google/gvisor | Skip UDPMulticast Tests when net interfaces aren't found.
PiperOrigin-RevId: 326686761 |
259,896 | 14.08.2020 14:47:19 | 25,200 | af433e159dbf07b084c0f05e65ec646c056033a7 | Update README for packetimpact | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/README.md",
"new_path": "test/packetimpact/README.md",
"diff": "@@ -30,7 +30,7 @@ $ make load-packetimpact\nRun a test, e.g. `fin_wait2_timeout`, against Linux:\n```bash\n-$ bazel test //test/packetimpact/tests:fin_wait2_timeout_linux_test\n+$ bazel test //test/packetimpact/tests:fin_wait2_timeout_native_test\n```\nRun the same test, but against gVisor:\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update README for packetimpact
PiperOrigin-RevId: 326733912 |
259,884 | 14.08.2020 16:21:29 | 25,200 | 3f523b3bbcf5ef7f37bb247bd4c5727711c70ba9 | Handle URLs better in issue reviver
Handle urls ending in /
Add some url parsing tests | [
{
"change_type": "MODIFY",
"old_path": "tools/issue_reviver/github/BUILD",
"new_path": "tools/issue_reviver/github/BUILD",
"diff": "-load(\"//tools:defs.bzl\", \"go_library\")\n+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\npackage(licenses = [\"notice\"])\n@@ -15,3 +15,10 @@ go_library(\n\"@org_golang_x_oauth2//:go_default_library\",\n],\n)\n+\n+go_test(\n+ name = \"github_test\",\n+ size = \"small\",\n+ srcs = [\"github_test.go\"],\n+ library = \":github\",\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/issue_reviver/github/github.go",
"new_path": "tools/issue_reviver/github/github.go",
"diff": "@@ -85,18 +85,13 @@ func (b *Bugger) load(token string) error {\n// Activate implements reviver.Bugger.\nfunc (b *Bugger) Activate(todo *reviver.Todo) (bool, error) {\n- const prefix = \"gvisor.dev/issue/\"\n-\n- // First check if I can handle the TODO.\n- idStr := strings.TrimPrefix(todo.Issue, prefix)\n- if len(todo.Issue) == len(idStr) {\n- return false, nil\n- }\n-\n- id, err := strconv.Atoi(idStr)\n+ id, err := parseIssueNo(todo.Issue)\nif err != nil {\nreturn true, err\n}\n+ if id <= 0 {\n+ return false, nil\n+ }\n// Check against active issues cache.\nif _, ok := b.issues[id]; ok {\n@@ -115,7 +110,7 @@ func (b *Bugger) Activate(todo *reviver.Todo) (bool, error) {\nl.File, l.Line, b.owner, b.repo, l.File, l.Line, l.Comment)\n}\nfmt.Fprintf(&comment,\n- \"\\n\\nSearch [TODO](https://github.com/%s/%s/search?q=%%22%s%d%%22)\", b.owner, b.repo, prefix, id)\n+ \"\\n\\nSearch [TODO](https://github.com/%s/%s/search?q=%%22%s%%22)\", b.owner, b.repo, todo.Issue)\nif b.dryRun {\nfmt.Printf(\"[dry-run: skipping change to issue %d]\\n%s\\n=======================\\n\", id, comment.String())\n@@ -140,6 +135,23 @@ func (b *Bugger) Activate(todo *reviver.Todo) (bool, error) {\nreturn true, nil\n}\n+// parseIssueNo parses the issue number out of the issue url.\n+func parseIssueNo(url string) (int, error) {\n+ const prefix = \"gvisor.dev/issue/\"\n+\n+ // First check if I can handle the TODO.\n+ idStr := strings.TrimPrefix(url, prefix)\n+ if len(url) == len(idStr) {\n+ return 0, nil\n+ }\n+\n+ id, err := strconv.ParseInt(strings.TrimRight(idStr, \"/\"), 10, 64)\n+ if err != nil {\n+ return 0, err\n+ }\n+ return int(id), nil\n+}\n+\nfunc processAllPages(fn func(github.ListOptions) (*github.Response, error)) error {\nopts := github.ListOptions{PerPage: 1000}\nfor {\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/issue_reviver/github/github_test.go",
"diff": "+// Copyright 2020 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 github\n+\n+import (\n+ \"testing\"\n+)\n+\n+func TestParseIssueNo(t *testing.T) {\n+ testCases := []struct {\n+ issue string\n+ expectErr bool\n+ expected int\n+ }{\n+ {\n+ issue: \"gvisor.dev/issue/123\",\n+ expected: 123,\n+ },\n+ {\n+ issue: \"gvisor.dev/issue/123/\",\n+ expected: 123,\n+ },\n+ {\n+ issue: \"not a url\",\n+ expected: 0,\n+ },\n+ {\n+ issue: \"gvisor.dev/issue//\",\n+ expectErr: true,\n+ },\n+ }\n+\n+ for _, tc := range testCases {\n+ t.Run(tc.issue, func(t *testing.T) {\n+ id, err := parseIssueNo(tc.issue)\n+ if err != nil && !tc.expectErr {\n+ t.Errorf(\"got error: %v\", err)\n+ } else if tc.expected != id {\n+ t.Errorf(\"got: %v, want: %v\", id, tc.expected)\n+ }\n+ })\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/issue_reviver/reviver/reviver.go",
"new_path": "tools/issue_reviver/reviver/reviver.go",
"diff": "@@ -26,7 +26,7 @@ import (\n\"sync\"\n)\n-// This is how a TODO looks like.\n+// regexTodo matches a TODO or FIXME comment.\nvar regexTodo = regexp.MustCompile(`(\\/\\/|#)\\s*(TODO|FIXME)\\(([a-zA-Z0-9.\\/]+)\\):\\s*(.+)`)\n// Bugger interface is called for every TODO found in the code. If it can handle\n"
}
] | Go | Apache License 2.0 | google/gvisor | Handle URLs better in issue reviver
- Handle urls ending in /
- Add some url parsing tests
PiperOrigin-RevId: 326750183 |
260,004 | 15.08.2020 00:04:30 | 25,200 | 9a7b5830aa063895f67ca0fdf653a46906374613 | Don't support address ranges
Previously the netstack supported assignment of a range of addresses.
This feature is not used so remove it. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -56,7 +56,6 @@ type NIC struct {\npromiscuous bool\nprimary map[tcpip.NetworkProtocolNumber][]*referencedNetworkEndpoint\nendpoints map[NetworkEndpointID]*referencedNetworkEndpoint\n- addressRanges []tcpip.Subnet\nmcastJoins map[NetworkEndpointID]uint32\n// packetEPs is protected by mu, but the contained PacketEndpoint\n// values are not.\n@@ -670,25 +669,6 @@ func (n *NIC) getRefOrCreateTemp(protocol tcpip.NetworkProtocolNumber, address t\n// A usable reference was not found, create a temporary one if requested by\n// the caller or if the address is found in the NIC's subnets.\ncreateTempEP := spoofingOrPromiscuous\n- if !createTempEP {\n- for _, sn := range n.mu.addressRanges {\n- // Skip the subnet address.\n- if address == sn.ID() {\n- continue\n- }\n- // For now just skip the broadcast address, until we support it.\n- // FIXME(b/137608825): Add support for sending/receiving directed\n- // (subnet) broadcast.\n- if address == sn.Broadcast() {\n- continue\n- }\n- if sn.Contains(address) {\n- createTempEP = true\n- break\n- }\n- }\n- }\n-\nn.mu.RUnlock()\nif !createTempEP {\n@@ -982,38 +962,11 @@ func (n *NIC) primaryAddress(proto tcpip.NetworkProtocolNumber) tcpip.AddressWit\nreturn tcpip.AddressWithPrefix{}\n}\n-// AddAddressRange adds a range of addresses to n, so that it starts accepting\n-// packets targeted at the given addresses and network protocol. The range is\n-// given by a subnet address, and all addresses contained in the subnet are\n-// used except for the subnet address itself and the subnet's broadcast\n-// address.\n-func (n *NIC) AddAddressRange(protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet) {\n- n.mu.Lock()\n- n.mu.addressRanges = append(n.mu.addressRanges, subnet)\n- n.mu.Unlock()\n-}\n-\n-// RemoveAddressRange removes the given address range from n.\n-func (n *NIC) RemoveAddressRange(subnet tcpip.Subnet) {\n- n.mu.Lock()\n-\n- // Use the same underlying array.\n- tmp := n.mu.addressRanges[:0]\n- for _, sub := range n.mu.addressRanges {\n- if sub != subnet {\n- tmp = append(tmp, sub)\n- }\n- }\n- n.mu.addressRanges = tmp\n-\n- n.mu.Unlock()\n-}\n-\n// AddressRanges returns the Subnets associated with this NIC.\nfunc (n *NIC) AddressRanges() []tcpip.Subnet {\nn.mu.RLock()\ndefer n.mu.RUnlock()\n- sns := make([]tcpip.Subnet, 0, len(n.mu.addressRanges)+len(n.mu.endpoints))\n+ sns := make([]tcpip.Subnet, 0, len(n.mu.endpoints))\nfor nid := range n.mu.endpoints {\nsn, err := tcpip.NewSubnet(nid.LocalAddress, tcpip.AddressMask(strings.Repeat(\"\\xff\", len(nid.LocalAddress))))\nif err != nil {\n@@ -1023,7 +976,7 @@ func (n *NIC) AddressRanges() []tcpip.Subnet {\n}\nsns = append(sns, sn)\n}\n- return append(sns, n.mu.addressRanges...)\n+ return sns\n}\n// insertPrimaryEndpointLocked adds r to n's primary endpoint list as required\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -1230,35 +1230,6 @@ func (s *Stack) AddProtocolAddressWithOptions(id tcpip.NICID, protocolAddress tc\nreturn nic.AddAddress(protocolAddress, peb)\n}\n-// AddAddressRange adds a range of addresses to the specified NIC. The range is\n-// given by a subnet address, and all addresses contained in the subnet are\n-// used except for the subnet address itself and the subnet's broadcast\n-// address.\n-func (s *Stack) AddAddressRange(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet) *tcpip.Error {\n- s.mu.RLock()\n- defer s.mu.RUnlock()\n-\n- if nic, ok := s.nics[id]; ok {\n- nic.AddAddressRange(protocol, subnet)\n- return nil\n- }\n-\n- return tcpip.ErrUnknownNICID\n-}\n-\n-// RemoveAddressRange removes the range of addresses from the specified NIC.\n-func (s *Stack) RemoveAddressRange(id tcpip.NICID, subnet tcpip.Subnet) *tcpip.Error {\n- s.mu.RLock()\n- defer s.mu.RUnlock()\n-\n- if nic, ok := s.nics[id]; ok {\n- nic.RemoveAddressRange(subnet)\n- return nil\n- }\n-\n- return tcpip.ErrUnknownNICID\n-}\n-\n// RemoveAddress removes an existing network-layer address from the specified\n// NIC.\nfunc (s *Stack) RemoveAddress(id tcpip.NICID, addr tcpip.Address) *tcpip.Error {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -23,7 +23,6 @@ import (\n\"math\"\n\"net\"\n\"sort\"\n- \"strings\"\n\"testing\"\n\"time\"\n@@ -1641,149 +1640,6 @@ func TestMulticastOrIPv6LinkLocalNeedsNoRoute(t *testing.T) {\n}\n}\n-// Add a range of addresses, then check that a packet is delivered.\n-func TestAddressRangeAcceptsMatchingPacket(t *testing.T) {\n- s := stack.New(stack.Options{\n- NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},\n- })\n-\n- ep := channel.New(10, defaultMTU, \"\")\n- if err := s.CreateNIC(1, ep); err != nil {\n- t.Fatal(\"CreateNIC failed:\", err)\n- }\n-\n- {\n- subnet, err := tcpip.NewSubnet(\"\\x00\", \"\\x00\")\n- if err != nil {\n- t.Fatal(err)\n- }\n- s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: \"\\x00\", NIC: 1}})\n- }\n-\n- fakeNet := s.NetworkProtocolInstance(fakeNetNumber).(*fakeNetworkProtocol)\n-\n- buf := buffer.NewView(30)\n-\n- const localAddrByte byte = 0x01\n- buf[dstAddrOffset] = localAddrByte\n- subnet, err := tcpip.NewSubnet(tcpip.Address(\"\\x00\"), tcpip.AddressMask(\"\\xF0\"))\n- if err != nil {\n- t.Fatal(\"NewSubnet failed:\", err)\n- }\n- if err := s.AddAddressRange(1, fakeNetNumber, subnet); err != nil {\n- t.Fatal(\"AddAddressRange failed:\", err)\n- }\n-\n- testRecv(t, fakeNet, localAddrByte, ep, buf)\n-}\n-\n-func testNicForAddressRange(t *testing.T, nicID tcpip.NICID, s *stack.Stack, subnet tcpip.Subnet, rangeExists bool) {\n- t.Helper()\n-\n- // Loop over all addresses and check them.\n- numOfAddresses := 1 << uint(8-subnet.Prefix())\n- if numOfAddresses < 1 || numOfAddresses > 255 {\n- t.Fatalf(\"got numOfAddresses = %d, want = [1 .. 255] (subnet=%s)\", numOfAddresses, subnet)\n- }\n-\n- addrBytes := []byte(subnet.ID())\n- for i := 0; i < numOfAddresses; i++ {\n- addr := tcpip.Address(addrBytes)\n- wantNicID := nicID\n- // The subnet and broadcast addresses are skipped.\n- if !rangeExists || addr == subnet.ID() || addr == subnet.Broadcast() {\n- wantNicID = 0\n- }\n- if gotNicID := s.CheckLocalAddress(0, fakeNetNumber, addr); gotNicID != wantNicID {\n- t.Errorf(\"got CheckLocalAddress(0, %d, %s) = %d, want = %d\", fakeNetNumber, addr, gotNicID, wantNicID)\n- }\n- addrBytes[0]++\n- }\n-\n- // Trying the next address should always fail since it is outside the range.\n- if gotNicID := s.CheckLocalAddress(0, fakeNetNumber, tcpip.Address(addrBytes)); gotNicID != 0 {\n- t.Errorf(\"got CheckLocalAddress(0, %d, %s) = %d, want = 0\", fakeNetNumber, tcpip.Address(addrBytes), gotNicID)\n- }\n-}\n-\n-// Set a range of addresses, then remove it again, and check at each step that\n-// CheckLocalAddress returns the correct NIC for each address or zero if not\n-// existent.\n-func TestCheckLocalAddressForSubnet(t *testing.T) {\n- const nicID tcpip.NICID = 1\n- s := stack.New(stack.Options{\n- NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},\n- })\n-\n- ep := channel.New(10, defaultMTU, \"\")\n- if err := s.CreateNIC(nicID, ep); err != nil {\n- t.Fatal(\"CreateNIC failed:\", err)\n- }\n-\n- {\n- subnet, err := tcpip.NewSubnet(\"\\x00\", \"\\x00\")\n- if err != nil {\n- t.Fatal(err)\n- }\n- s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: \"\\x00\", NIC: nicID}})\n- }\n-\n- subnet, err := tcpip.NewSubnet(tcpip.Address(\"\\xa0\"), tcpip.AddressMask(\"\\xf0\"))\n- if err != nil {\n- t.Fatal(\"NewSubnet failed:\", err)\n- }\n-\n- testNicForAddressRange(t, nicID, s, subnet, false /* rangeExists */)\n-\n- if err := s.AddAddressRange(nicID, fakeNetNumber, subnet); err != nil {\n- t.Fatal(\"AddAddressRange failed:\", err)\n- }\n-\n- testNicForAddressRange(t, nicID, s, subnet, true /* rangeExists */)\n-\n- if err := s.RemoveAddressRange(nicID, subnet); err != nil {\n- t.Fatal(\"RemoveAddressRange failed:\", err)\n- }\n-\n- testNicForAddressRange(t, nicID, s, subnet, false /* rangeExists */)\n-}\n-\n-// Set a range of addresses, then send a packet to a destination outside the\n-// range and then check it doesn't get delivered.\n-func TestAddressRangeRejectsNonmatchingPacket(t *testing.T) {\n- s := stack.New(stack.Options{\n- NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},\n- })\n-\n- ep := channel.New(10, defaultMTU, \"\")\n- if err := s.CreateNIC(1, ep); err != nil {\n- t.Fatal(\"CreateNIC failed:\", err)\n- }\n-\n- {\n- subnet, err := tcpip.NewSubnet(\"\\x00\", \"\\x00\")\n- if err != nil {\n- t.Fatal(err)\n- }\n- s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: \"\\x00\", NIC: 1}})\n- }\n-\n- fakeNet := s.NetworkProtocolInstance(fakeNetNumber).(*fakeNetworkProtocol)\n-\n- buf := buffer.NewView(30)\n-\n- const localAddrByte byte = 0x01\n- buf[dstAddrOffset] = localAddrByte\n- subnet, err := tcpip.NewSubnet(tcpip.Address(\"\\x10\"), tcpip.AddressMask(\"\\xF0\"))\n- if err != nil {\n- t.Fatal(\"NewSubnet failed:\", err)\n- }\n- if err := s.AddAddressRange(1, fakeNetNumber, subnet); err != nil {\n- t.Fatal(\"AddAddressRange failed:\", err)\n- }\n- testFailingRecv(t, fakeNet, localAddrByte, ep, buf)\n-}\n-\nfunc TestNetworkOptions(t *testing.T) {\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},\n@@ -1827,56 +1683,6 @@ func TestNetworkOptions(t *testing.T) {\n}\n}\n-func stackContainsAddressRange(s *stack.Stack, id tcpip.NICID, addrRange tcpip.Subnet) bool {\n- ranges, ok := s.NICAddressRanges()[id]\n- if !ok {\n- return false\n- }\n- for _, r := range ranges {\n- if r == addrRange {\n- return true\n- }\n- }\n- return false\n-}\n-\n-func TestAddresRangeAddRemove(t *testing.T) {\n- s := stack.New(stack.Options{\n- NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},\n- })\n- ep := channel.New(10, defaultMTU, \"\")\n- if err := s.CreateNIC(1, ep); err != nil {\n- t.Fatal(\"CreateNIC failed:\", err)\n- }\n-\n- addr := tcpip.Address(\"\\x01\\x01\\x01\\x01\")\n- mask := tcpip.AddressMask(strings.Repeat(\"\\xff\", len(addr)))\n- addrRange, err := tcpip.NewSubnet(addr, mask)\n- if err != nil {\n- t.Fatal(\"NewSubnet failed:\", err)\n- }\n-\n- if got, want := stackContainsAddressRange(s, 1, addrRange), false; got != want {\n- t.Fatalf(\"got stackContainsAddressRange(...) = %t, want = %t\", got, want)\n- }\n-\n- if err := s.AddAddressRange(1, fakeNetNumber, addrRange); err != nil {\n- t.Fatal(\"AddAddressRange failed:\", err)\n- }\n-\n- if got, want := stackContainsAddressRange(s, 1, addrRange), true; got != want {\n- t.Fatalf(\"got stackContainsAddressRange(...) = %t, want = %t\", got, want)\n- }\n-\n- if err := s.RemoveAddressRange(1, addrRange); err != nil {\n- t.Fatal(\"RemoveAddressRange failed:\", err)\n- }\n-\n- if got, want := stackContainsAddressRange(s, 1, addrRange), false; got != want {\n- t.Fatalf(\"got stackContainsAddressRange(...) = %t, want = %t\", got, want)\n- }\n-}\n-\nfunc TestGetMainNICAddressAddPrimaryNonPrimary(t *testing.T) {\nfor _, addrLen := range []int{4, 16} {\nt.Run(fmt.Sprintf(\"addrLen=%d\", addrLen), func(t *testing.T) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't support address ranges
Previously the netstack supported assignment of a range of addresses.
This feature is not used so remove it.
PiperOrigin-RevId: 326791119 |
259,907 | 17.08.2020 10:03:38 | 25,200 | 97263e505324b7d1c58a3daaac7175241921998f | [vfs] Return EIO when opening /dev/tty.
This is in compliance with VFS1. See pkg/sentry/fs/dev/tty.go in the struct
ttyInodeOperations.
Fixes the failure of python runtime test_ioctl.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/devices/ttydev/BUILD",
"new_path": "pkg/sentry/devices/ttydev/BUILD",
"diff": "@@ -11,6 +11,6 @@ go_library(\n\"//pkg/context\",\n\"//pkg/sentry/fsimpl/devtmpfs\",\n\"//pkg/sentry/vfs\",\n- \"//pkg/usermem\",\n+ \"//pkg/syserror\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/devices/ttydev/ttydev.go",
"new_path": "pkg/sentry/devices/ttydev/ttydev.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// Package ttydev implements devices for /dev/tty and (eventually)\n-// /dev/console.\n-//\n-// TODO(b/159623826): Support /dev/console.\n+// Package ttydev implements an unopenable vfs.Device for /dev/tty.\npackage ttydev\nimport (\n@@ -23,7 +20,7 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/devtmpfs\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n- \"gvisor.dev/gvisor/pkg/usermem\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n)\nconst (\n@@ -37,44 +34,7 @@ type ttyDevice struct{}\n// Open implements vfs.Device.Open.\nfunc (ttyDevice) Open(ctx context.Context, mnt *vfs.Mount, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n- fd := &ttyFD{}\n- if err := fd.vfsfd.Init(fd, opts.Flags, mnt, vfsd, &vfs.FileDescriptionOptions{\n- UseDentryMetadata: true,\n- }); err != nil {\n- return nil, err\n- }\n- return &fd.vfsfd, nil\n-}\n-\n-// ttyFD implements vfs.FileDescriptionImpl for /dev/tty.\n-type ttyFD struct {\n- vfsfd vfs.FileDescription\n- vfs.FileDescriptionDefaultImpl\n- vfs.DentryMetadataFileDescriptionImpl\n- vfs.NoLockFD\n-}\n-\n-// Release implements vfs.FileDescriptionImpl.Release.\n-func (fd *ttyFD) Release(context.Context) {}\n-\n-// PRead implements vfs.FileDescriptionImpl.PRead.\n-func (fd *ttyFD) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\n- return 0, nil\n-}\n-\n-// Read implements vfs.FileDescriptionImpl.Read.\n-func (fd *ttyFD) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\n- return 0, nil\n-}\n-\n-// PWrite implements vfs.FileDescriptionImpl.PWrite.\n-func (fd *ttyFD) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\n- return src.NumBytes(), nil\n-}\n-\n-// Write implements vfs.FileDescriptionImpl.Write.\n-func (fd *ttyFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\n- return src.NumBytes(), nil\n+ return nil, syserror.EIO\n}\n// Register registers all devices implemented by this package in vfsObj.\n"
}
] | Go | Apache License 2.0 | google/gvisor | [vfs] Return EIO when opening /dev/tty.
This is in compliance with VFS1. See pkg/sentry/fs/dev/tty.go in the struct
ttyInodeOperations.
Fixes the failure of python runtime test_ioctl.
Updates #3515
PiperOrigin-RevId: 327042758 |
259,951 | 17.08.2020 10:04:03 | 25,200 | 58154194b3e472cf476be6bf0530bf271d1d29f8 | Add a unit test for out of order IP reassembly | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"diff": "@@ -627,6 +627,28 @@ func TestReceiveFragments(t *testing.T) {\n},\nexpectedPayloads: [][]byte{udpPayload1Addr1ToAddr2},\n},\n+ {\n+ name: \"Two fragments out of order\",\n+ fragments: []fragmentData{\n+ {\n+ srcAddr: addr1,\n+ dstAddr: addr2,\n+ id: 1,\n+ flags: 0,\n+ fragmentOffset: 64,\n+ payload: ipv4Payload1Addr1ToAddr2[64:],\n+ },\n+ {\n+ srcAddr: addr1,\n+ dstAddr: addr2,\n+ id: 1,\n+ flags: header.IPv4FlagMoreFragments,\n+ fragmentOffset: 0,\n+ payload: ipv4Payload1Addr1ToAddr2[:64],\n+ },\n+ },\n+ expectedPayloads: [][]byte{udpPayload1Addr1ToAddr2},\n+ },\n{\nname: \"Two fragments with last fragment size not a multiple of fragment block size\",\nfragments: []fragmentData{\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6_test.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6_test.go",
"diff": "@@ -827,6 +827,44 @@ func TestReceiveIPv6Fragments(t *testing.T) {\n},\nexpectedPayloads: [][]byte{udpPayload1Addr1ToAddr2},\n},\n+ {\n+ name: \"Two fragments out of order\",\n+ fragments: []fragmentData{\n+ {\n+ srcAddr: addr1,\n+ dstAddr: addr2,\n+ nextHdr: fragmentExtHdrID,\n+ data: buffer.NewVectorisedView(\n+ fragmentExtHdrLen+len(ipv6Payload1Addr1ToAddr2)-64,\n+ []buffer.View{\n+ // Fragment extension header.\n+ //\n+ // Fragment offset = 8, More = false, ID = 1\n+ buffer.View([]byte{uint8(header.UDPProtocolNumber), 0, 0, 64, 0, 0, 0, 1}),\n+\n+ ipv6Payload1Addr1ToAddr2[64:],\n+ },\n+ ),\n+ },\n+ {\n+ srcAddr: addr1,\n+ dstAddr: addr2,\n+ nextHdr: fragmentExtHdrID,\n+ data: buffer.NewVectorisedView(\n+ fragmentExtHdrLen+64,\n+ []buffer.View{\n+ // Fragment extension header.\n+ //\n+ // Fragment offset = 0, More = true, ID = 1\n+ buffer.View([]byte{uint8(header.UDPProtocolNumber), 0, 0, 1, 0, 0, 0, 1}),\n+\n+ ipv6Payload1Addr1ToAddr2[:64],\n+ },\n+ ),\n+ },\n+ },\n+ expectedPayloads: [][]byte{udpPayload1Addr1ToAddr2},\n+ },\n{\nname: \"Two fragments with last fragment size not a multiple of fragment block size\",\nfragments: []fragmentData{\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add a unit test for out of order IP reassembly
PiperOrigin-RevId: 327042869 |
259,860 | 17.08.2020 11:40:08 | 25,200 | 3bd066d5032c297e501f5c71be301ffa2fe9ed34 | Remove weak references from unix sockets.
The abstract socket namespace no longer holds any references on sockets.
Instead, TryIncRef() is used when a socket is being retrieved in
BoundEndpoint(). Abstract sockets are now responsible for removing themselves
from the namespace they are in, when they are destroyed.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/refs_vfs2/BUILD",
"new_path": "pkg/refs_vfs2/BUILD",
"diff": "@@ -19,10 +19,8 @@ go_template(\n)\ngo_library(\n- name = \"refs\",\n- srcs = [\n- \"refs.go\",\n- ],\n+ name = \"refs_vfs2\",\n+ srcs = [\"refs.go\"],\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\"//pkg/context\"],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/refs_vfs2/refs.go",
"new_path": "pkg/refs_vfs2/refs.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// Package refs defines an interface for a reference-counted object.\n-package refs\n+// Package refs_vfs2 defines an interface for a reference-counted object.\n+package refs_vfs2\nimport (\n\"gvisor.dev/gvisor/pkg/context\"\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/BUILD",
"new_path": "pkg/sentry/kernel/BUILD",
"diff": "@@ -163,6 +163,7 @@ go_library(\n\"//pkg/log\",\n\"//pkg/metric\",\n\"//pkg/refs\",\n+ \"//pkg/refs_vfs2\",\n\"//pkg/safemem\",\n\"//pkg/secio\",\n\"//pkg/sentry/arch\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/abstract_socket_namespace.go",
"new_path": "pkg/sentry/kernel/abstract_socket_namespace.go",
"diff": "package kernel\nimport (\n+ \"fmt\"\n\"syscall\"\n\"gvisor.dev/gvisor/pkg/context\"\n- \"gvisor.dev/gvisor/pkg/refs\"\n+ \"gvisor.dev/gvisor/pkg/refs_vfs2\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n\"gvisor.dev/gvisor/pkg/sync\"\n)\n@@ -26,27 +27,22 @@ import (\n// +stateify savable\ntype abstractEndpoint struct {\nep transport.BoundEndpoint\n- wr *refs.WeakRef\n+ socket refs_vfs2.RefCounter\nname string\nns *AbstractSocketNamespace\n}\n-// WeakRefGone implements refs.WeakRefUser.WeakRefGone.\n-func (e *abstractEndpoint) WeakRefGone(context.Context) {\n- e.ns.mu.Lock()\n- if e.ns.endpoints[e.name].ep == e.ep {\n- delete(e.ns.endpoints, e.name)\n- }\n- e.ns.mu.Unlock()\n-}\n-\n// AbstractSocketNamespace is used to implement the Linux abstract socket functionality.\n//\n// +stateify savable\ntype AbstractSocketNamespace struct {\nmu sync.Mutex `state:\"nosave\"`\n- // Keeps mapping from name to endpoint.\n+ // Keeps a mapping from name to endpoint. AbstractSocketNamespace does not hold\n+ // any references on any sockets that it contains; when retrieving a socket,\n+ // TryIncRef() must be called in case the socket is concurrently being\n+ // destroyed. It is the responsibility of the socket to remove itself from the\n+ // abstract socket namespace when it is destroyed.\nendpoints map[string]abstractEndpoint\n}\n@@ -58,15 +54,15 @@ func NewAbstractSocketNamespace() *AbstractSocketNamespace {\n}\n// A boundEndpoint wraps a transport.BoundEndpoint to maintain a reference on\n-// its backing object.\n+// its backing socket.\ntype boundEndpoint struct {\ntransport.BoundEndpoint\n- rc refs.RefCounter\n+ socket refs_vfs2.RefCounter\n}\n// Release implements transport.BoundEndpoint.Release.\nfunc (e *boundEndpoint) Release(ctx context.Context) {\n- e.rc.DecRef(ctx)\n+ e.socket.DecRef(ctx)\ne.BoundEndpoint.Release(ctx)\n}\n@@ -81,32 +77,59 @@ func (a *AbstractSocketNamespace) BoundEndpoint(name string) transport.BoundEndp\nreturn nil\n}\n- rc := ep.wr.Get()\n- if rc == nil {\n- delete(a.endpoints, name)\n+ if !ep.socket.TryIncRef() {\n+ // The socket has reached zero references and is being destroyed.\nreturn nil\n}\n- return &boundEndpoint{ep.ep, rc}\n+ return &boundEndpoint{ep.ep, ep.socket}\n}\n// Bind binds the given socket.\n//\n-// When the last reference managed by rc is dropped, ep may be removed from the\n+// When the last reference managed by socket is dropped, ep may be removed from the\n// namespace.\n-func (a *AbstractSocketNamespace) Bind(ctx context.Context, name string, ep transport.BoundEndpoint, rc refs.RefCounter) error {\n+func (a *AbstractSocketNamespace) Bind(ctx context.Context, name string, ep transport.BoundEndpoint, socket refs_vfs2.RefCounter) error {\na.mu.Lock()\ndefer a.mu.Unlock()\n+ // Check if there is already a socket (which has not yet been destroyed) bound at name.\nif ep, ok := a.endpoints[name]; ok {\n- if rc := ep.wr.Get(); rc != nil {\n- rc.DecRef(ctx)\n+ if ep.socket.TryIncRef() {\n+ ep.socket.DecRef(ctx)\nreturn syscall.EADDRINUSE\n}\n}\nae := abstractEndpoint{ep: ep, name: name, ns: a}\n- ae.wr = refs.NewWeakRef(rc, &ae)\n+ ae.socket = socket\na.endpoints[name] = ae\nreturn nil\n}\n+\n+// Remove removes the specified socket at name from the abstract socket\n+// namespace, if it has not yet been replaced.\n+func (a *AbstractSocketNamespace) Remove(name string, socket refs_vfs2.RefCounter) {\n+ a.mu.Lock()\n+ defer a.mu.Unlock()\n+\n+ ep, ok := a.endpoints[name]\n+ if !ok {\n+ // We never delete a map entry apart from a socket's destructor (although the\n+ // map entry may be overwritten). Therefore, a socket should exist, even if it\n+ // may not be the one we expect.\n+ panic(fmt.Sprintf(\"expected socket to exist at '%s' in abstract socket namespace\", name))\n+ }\n+\n+ // A Bind() operation may race with callers of Remove(), e.g. in the\n+ // following case:\n+ // socket1 reaches zero references and begins destruction\n+ // a.Bind(\"foo\", ep, socket2) replaces socket1 with socket2\n+ // socket1's destructor calls a.Remove(\"foo\", socket1)\n+ //\n+ // Therefore, we need to check that the socket at name is what we expect\n+ // before modifying the map.\n+ if ep.socket == socket {\n+ delete(a.endpoints, name)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/BUILD",
"new_path": "pkg/sentry/socket/unix/BUILD",
"diff": "load(\"//tools:defs.bzl\", \"go_library\")\n+load(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\npackage(licenses = [\"notice\"])\n+go_template_instance(\n+ name = \"socket_refs\",\n+ out = \"socket_refs.go\",\n+ package = \"unix\",\n+ prefix = \"socketOpsCommon\",\n+ template = \"//pkg/refs_vfs2:refs_template\",\n+ types = {\n+ \"T\": \"socketOpsCommon\",\n+ },\n+)\n+\ngo_library(\nname = \"unix\",\nsrcs = [\n\"device.go\",\n\"io.go\",\n+ \"socket_refs.go\",\n\"unix.go\",\n\"unix_vfs2.go\",\n],\n@@ -15,6 +28,7 @@ go_library(\n\"//pkg/abi/linux\",\n\"//pkg/context\",\n\"//pkg/fspath\",\n+ \"//pkg/log\",\n\"//pkg/refs\",\n\"//pkg/safemem\",\n\"//pkg/sentry/arch\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/unix.go",
"new_path": "pkg/sentry/socket/unix/unix.go",
"diff": "@@ -24,7 +24,6 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n- \"gvisor.dev/gvisor/pkg/refs\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/fsutil\"\n@@ -80,7 +79,7 @@ func NewWithDirent(ctx context.Context, d *fs.Dirent, ep transport.Endpoint, sty\nstype: stype,\n},\n}\n- s.EnableLeakCheck(\"unix.SocketOperations\")\n+ s.EnableLeakCheck()\nreturn fs.NewFile(ctx, d, flags, &s)\n}\n@@ -89,17 +88,26 @@ func NewWithDirent(ctx context.Context, d *fs.Dirent, ep transport.Endpoint, sty\n//\n// +stateify savable\ntype socketOpsCommon struct {\n- refs.AtomicRefCount\n+ socketOpsCommonRefs\nsocket.SendReceiveTimeout\nep transport.Endpoint\nstype linux.SockType\n+\n+ // abstractName and abstractNamespace indicate the name and namespace of the\n+ // socket if it is bound to an abstract socket namespace. Once the socket is\n+ // bound, they cannot be modified.\n+ abstractName string\n+ abstractNamespace *kernel.AbstractSocketNamespace\n}\n// DecRef implements RefCounter.DecRef.\nfunc (s *socketOpsCommon) DecRef(ctx context.Context) {\n- s.DecRefWithDestructor(ctx, func(context.Context) {\n+ s.socketOpsCommonRefs.DecRef(func() {\ns.ep.Close(ctx)\n+ if s.abstractNamespace != nil {\n+ s.abstractNamespace.Remove(s.abstractName, s)\n+ }\n})\n}\n@@ -284,10 +292,14 @@ func (s *SocketOperations) Bind(t *kernel.Task, sockaddr []byte) *syserr.Error {\nif t.IsNetworkNamespaced() {\nreturn syserr.ErrInvalidEndpointState\n}\n- if err := t.AbstractSockets().Bind(t, p[1:], bep, s); err != nil {\n+ asn := t.AbstractSockets()\n+ name := p[1:]\n+ if err := asn.Bind(t, name, bep, s); err != nil {\n// syserr.ErrPortInUse corresponds to EADDRINUSE.\nreturn syserr.ErrPortInUse\n}\n+ s.abstractName = name\n+ s.abstractNamespace = asn\n} else {\n// The parent and name.\nvar d *fs.Dirent\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/unix_vfs2.go",
"new_path": "pkg/sentry/socket/unix/unix_vfs2.go",
"diff": "@@ -183,10 +183,14 @@ func (s *SocketVFS2) Bind(t *kernel.Task, sockaddr []byte) *syserr.Error {\nif t.IsNetworkNamespaced() {\nreturn syserr.ErrInvalidEndpointState\n}\n- if err := t.AbstractSockets().Bind(t, p[1:], bep, s); err != nil {\n+ asn := t.AbstractSockets()\n+ name := p[1:]\n+ if err := asn.Bind(t, name, bep, s); err != nil {\n// syserr.ErrPortInUse corresponds to EADDRINUSE.\nreturn syserr.ErrPortInUse\n}\n+ s.abstractName = name\n+ s.abstractNamespace = asn\n} else {\npath := fspath.Parse(p)\nroot := t.FSContext().RootDirectoryVFS2()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove weak references from unix sockets.
The abstract socket namespace no longer holds any references on sockets.
Instead, TryIncRef() is used when a socket is being retrieved in
BoundEndpoint(). Abstract sockets are now responsible for removing themselves
from the namespace they are in, when they are destroyed.
Updates #1486.
PiperOrigin-RevId: 327064173 |
260,004 | 17.08.2020 12:27:59 | 25,200 | e3c4bbd10a93ac824af3204c520437f3d5ff470c | Remove address range functions
Should have been removed in cl/326791119 | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -19,7 +19,6 @@ import (\n\"math/rand\"\n\"reflect\"\n\"sort\"\n- \"strings\"\n\"sync/atomic\"\n\"gvisor.dev/gvisor/pkg/sync\"\n@@ -962,23 +961,6 @@ func (n *NIC) primaryAddress(proto tcpip.NetworkProtocolNumber) tcpip.AddressWit\nreturn tcpip.AddressWithPrefix{}\n}\n-// AddressRanges returns the Subnets associated with this NIC.\n-func (n *NIC) AddressRanges() []tcpip.Subnet {\n- n.mu.RLock()\n- defer n.mu.RUnlock()\n- sns := make([]tcpip.Subnet, 0, len(n.mu.endpoints))\n- for nid := range n.mu.endpoints {\n- sn, err := tcpip.NewSubnet(nid.LocalAddress, tcpip.AddressMask(strings.Repeat(\"\\xff\", len(nid.LocalAddress))))\n- if err != nil {\n- // This should never happen as the mask has been carefully crafted to\n- // match the address.\n- panic(\"Invalid endpoint subnet: \" + err.Error())\n- }\n- sns = append(sns, sn)\n- }\n- return sns\n-}\n-\n// insertPrimaryEndpointLocked adds r to n's primary endpoint list as required\n// by peb.\n//\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -1102,19 +1102,6 @@ func (s *Stack) removeNICLocked(id tcpip.NICID) *tcpip.Error {\nreturn nic.remove()\n}\n-// NICAddressRanges returns a map of NICIDs to their associated subnets.\n-func (s *Stack) NICAddressRanges() map[tcpip.NICID][]tcpip.Subnet {\n- s.mu.RLock()\n- defer s.mu.RUnlock()\n-\n- nics := map[tcpip.NICID][]tcpip.Subnet{}\n-\n- for id, nic := range s.nics {\n- nics[id] = append(nics[id], nic.AddressRanges()...)\n- }\n- return nics\n-}\n-\n// NICInfo captures the name and addresses assigned to a NIC.\ntype NICInfo struct {\nName string\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove address range functions
Should have been removed in cl/326791119
https://github.com/google/gvisor/commit/9a7b5830aa063895f67ca0fdf653a46906374613
PiperOrigin-RevId: 327074156 |
259,975 | 17.08.2020 14:01:38 | 25,200 | 988ab27058829fd2ccb550560a7651511d7b872a | Fix AllSocketPairTest for open source.
Setting timeouts for sockets on GCP images (debian) for usecs only
respects multiples of 4K. Set the test with a multiple of 4K with a comment. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_generic.cc",
"new_path": "test/syscalls/linux/socket_generic.cc",
"diff": "@@ -462,6 +462,7 @@ TEST_P(AllSocketPairTest, SendTimeoutDefault) {\nTEST_P(AllSocketPairTest, SetGetSendTimeout) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+ // tv_usec should be a multiple of 4000 to work on most systems.\ntimeval tv = {.tv_sec = 89, .tv_usec = 42000};\nEXPECT_THAT(\nsetsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)),\n@@ -472,8 +473,8 @@ TEST_P(AllSocketPairTest, SetGetSendTimeout) {\nEXPECT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO,\n&actual_tv, &len),\nSyscallSucceeds());\n- EXPECT_EQ(actual_tv.tv_sec, 89);\n- EXPECT_EQ(actual_tv.tv_usec, 42000);\n+ EXPECT_EQ(actual_tv.tv_sec, tv.tv_sec);\n+ EXPECT_EQ(actual_tv.tv_usec, tv.tv_usec);\n}\nTEST_P(AllSocketPairTest, SetGetSendTimeoutLargerArg) {\n@@ -484,8 +485,9 @@ TEST_P(AllSocketPairTest, SetGetSendTimeoutLargerArg) {\nint64_t extra_data;\n} ABSL_ATTRIBUTE_PACKED;\n+ // tv_usec should be a multiple of 4000 to work on most systems.\ntimeval_with_extra tv_extra = {\n- .tv = {.tv_sec = 0, .tv_usec = 123000},\n+ .tv = {.tv_sec = 0, .tv_usec = 124000},\n};\nEXPECT_THAT(setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO,\n@@ -497,8 +499,8 @@ TEST_P(AllSocketPairTest, SetGetSendTimeoutLargerArg) {\nEXPECT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO,\n&actual_tv, &len),\nSyscallSucceeds());\n- EXPECT_EQ(actual_tv.tv.tv_sec, 0);\n- EXPECT_EQ(actual_tv.tv.tv_usec, 123000);\n+ EXPECT_EQ(actual_tv.tv.tv_sec, tv_extra.tv.tv_sec);\n+ EXPECT_EQ(actual_tv.tv.tv_usec, tv_extra.tv.tv_usec);\n}\nTEST_P(AllSocketPairTest, SendTimeoutAllowsWrite) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix AllSocketPairTest for open source.
Setting timeouts for sockets on GCP images (debian) for usecs only
respects multiples of 4K. Set the test with a multiple of 4K with a comment.
PiperOrigin-RevId: 327093848 |
259,975 | 18.08.2020 09:52:53 | 25,200 | da5c2ea6dc4ea01c667bff88aa37f5efb39b704a | Fix return value for MMap Tests in OpenSource
Some systems return 128 + errno instead of just errno, which is the case
here. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/mmap.cc",
"new_path": "test/syscalls/linux/mmap.cc",
"diff": "#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n+using ::testing::AnyOf;\n+using ::testing::Eq;\nusing ::testing::Gt;\nnamespace gvisor {\n@@ -296,7 +298,8 @@ TEST_F(MMapTest, MapDevZeroSegfaultAfterUnmap) {\n};\nEXPECT_THAT(InForkedProcess(rest),\n- IsPosixErrorOkAndHolds(W_EXITCODE(0, SIGSEGV)));\n+ IsPosixErrorOkAndHolds(AnyOf(Eq(W_EXITCODE(0, SIGSEGV)),\n+ Eq(W_EXITCODE(0, 128 + SIGSEGV)))));\n}\nTEST_F(MMapTest, MapDevZeroUnaligned) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix return value for MMap Tests in OpenSource
Some systems return 128 + errno instead of just errno, which is the case
here.
PiperOrigin-RevId: 327247836 |
259,975 | 18.08.2020 09:53:47 | 25,200 | 673b6cc7fc4a99c8fb20f7becb91288ce98ae593 | Fix readahead test for opensource.
Skip InvalidOffset and InvalidLength for Linux as the test is invalid for
later Kernel versions.
Add UnsupportedFile test as this check is in all kernel versions. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1862,6 +1862,7 @@ cc_binary(\nsrcs = [\"readahead.cc\"],\nlinkstatic = 1,\ndeps = [\n+ \":socket_test_util\",\n\"//test/util:file_descriptor\",\ngtest,\n\"//test/util:temp_path\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/readahead.cc",
"new_path": "test/syscalls/linux/readahead.cc",
"diff": "#include <fcntl.h>\n#include \"gtest/gtest.h\"\n+#include \"test/syscalls/linux/socket_test_util.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n@@ -29,7 +30,15 @@ TEST(ReadaheadTest, InvalidFD) {\nEXPECT_THAT(readahead(-1, 1, 1), SyscallFailsWithErrno(EBADF));\n}\n+TEST(ReadaheadTest, UnsupportedFile) {\n+ FileDescriptor sock =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_UNIX, SOCK_STREAM, 0));\n+ ASSERT_THAT(readahead(sock.get(), 1, 1), SyscallFailsWithErrno(EINVAL));\n+}\n+\nTEST(ReadaheadTest, InvalidOffset) {\n+ // This test is not valid for some Linux Kernels.\n+ SKIP_IF(!IsRunningOnGvisor());\nconst TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\nconst FileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDWR));\n@@ -79,6 +88,8 @@ TEST(ReadaheadTest, WriteOnly) {\n}\nTEST(ReadaheadTest, InvalidSize) {\n+ // This test is not valid on some Linux kernels.\n+ SKIP_IF(!IsRunningOnGvisor());\nconst TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\nconst FileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDWR));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix readahead test for opensource.
Skip InvalidOffset and InvalidLength for Linux as the test is invalid for
later Kernel versions.
Add UnsupportedFile test as this check is in all kernel versions.
PiperOrigin-RevId: 327248035 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.