diff options
Diffstat (limited to 'runsc')
-rw-r--r-- | runsc/test/image/BUILD | 23 | ||||
-rw-r--r-- | runsc/test/image/image.go | 16 | ||||
-rw-r--r-- | runsc/test/image/image_test.go | 230 | ||||
-rw-r--r-- | runsc/test/image/latin10k.txt | 33 | ||||
-rw-r--r-- | runsc/test/testutil/testutil.go | 19 |
5 files changed, 321 insertions, 0 deletions
diff --git a/runsc/test/image/BUILD b/runsc/test/image/BUILD new file mode 100644 index 000000000..2876d4256 --- /dev/null +++ b/runsc/test/image/BUILD @@ -0,0 +1,23 @@ +package(licenses = ["notice"]) # Apache 2.0 + +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_test( + name = "image_test", + size = "small", + srcs = ["image_test.go"], + data = ["latin10k.txt"], + embed = [":image"], + tags = [ + # Requires docker and runsc to be configured before the test runs. + "manual", + "local", + ], + deps = ["//runsc/test/testutil"], +) + +go_library( + name = "image", + srcs = ["image.go"], + importpath = "gvisor.googlesource.com/gvisor/runsc/test/image", +) diff --git a/runsc/test/image/image.go b/runsc/test/image/image.go new file mode 100644 index 000000000..069d08013 --- /dev/null +++ b/runsc/test/image/image.go @@ -0,0 +1,16 @@ +// Copyright 2018 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package image is empty. See image_test.go for description. +package image diff --git a/runsc/test/image/image_test.go b/runsc/test/image/image_test.go new file mode 100644 index 000000000..08b1bf279 --- /dev/null +++ b/runsc/test/image/image_test.go @@ -0,0 +1,230 @@ +// Copyright 2018 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package image provides end-to-end image tests for runsc. These tests require +// docker and runsc to be installed on the machine. +// +// The tests expect the runtime name to be provided in the RUNSC_RUNTIME +// environment variable (default: runsc-test). +// +// Each test calls docker commands to start up a container, and tests that it is +// behaving properly, like connecting to a port or looking at the output. The +// container is killed and deleted at the end. +package image + +import ( + "fmt" + "io/ioutil" + "log" + "math/rand" + "net/http" + "os" + "os/exec" + "path" + "regexp" + "strconv" + "strings" + "testing" + "time" + + "gvisor.googlesource.com/gvisor/runsc/test/testutil" +) + +func init() { + rand.Seed(time.Now().UnixNano()) +} + +func runtime() string { + r := os.Getenv("RUNSC_RUNTIME") + if r == "" { + return "runsc-test" + } + return r +} + +func mountArg(source, target string) string { + return fmt.Sprintf("%s:%s", source, target) +} + +func getLocalPath(file string) string { + return path.Join(".", file) +} + +type docker struct { + runtime string + name string +} + +func makeDocker(namePrefix string) docker { + suffix := fmt.Sprintf("-%06d", rand.Int())[:7] + return docker{name: namePrefix + suffix, runtime: runtime()} +} + +// do executes docker command. +func (d *docker) do(args ...string) (string, error) { + cmd := exec.Command("docker", args...) + out, err := cmd.CombinedOutput() + if err != nil { + return "", fmt.Errorf("error executing docker %s: %v", args, err) + } + return string(out), nil +} + +// run calls 'docker run' with the arguments provided. +func (d *docker) run(args ...string) (string, error) { + a := []string{"run", "--runtime", d.runtime, "--name", d.name, "-d"} + a = append(a, args...) + return d.do(a...) +} + +// cleanUp kills and deletes the container. +func (d *docker) cleanUp() error { + if _, err := d.do("kill", d.name); err != nil { + return fmt.Errorf("error killing container %q: %v", d.name, err) + } + if _, err := d.do("rm", d.name); err != nil { + return fmt.Errorf("error deleting container %q: %v", d.name, err) + } + return nil +} + +// findPort returns the host port that is mapped to 'sandboxPort'. This calls +// docker to allocate a free port in the host and prevent conflicts. +func (d *docker) findPort(sandboxPort int) (int, error) { + format := fmt.Sprintf(`{{ (index (index .NetworkSettings.Ports "%d/tcp") 0).HostPort }}`, sandboxPort) + out, err := d.do("inspect", "-f", format, d.name) + if err != nil { + return -1, fmt.Errorf("error retrieving port: %v", err) + } + port, err := strconv.Atoi(strings.TrimSuffix(string(out), "\n")) + if err != nil { + return -1, fmt.Errorf("error parsing port %q: %v", out, err) + } + return port, nil +} + +// waitForOutput calls 'docker logs' to retrieve containers output and searches +// for the given pattern. +func (d *docker) waitForOutput(pattern string, timeout time.Duration) error { + re := regexp.MustCompile(pattern) + for exp := time.Now().Add(timeout); time.Now().Before(exp); { + out, err := d.do("logs", d.name) + if err != nil { + return err + } + if re.MatchString(out) { + return nil + } + time.Sleep(10 * time.Millisecond) + } + return fmt.Errorf("timeout waiting for output %q", re.String()) +} + +func TestHelloWorld(t *testing.T) { + d := makeDocker("hello-test") + if out, err := d.run("hello-world"); err != nil { + t.Fatalf("docker run failed: %v\nout: %s", err, out) + } + defer d.cleanUp() + + if err := d.waitForOutput(".*Hello from Docker!.*", 5*time.Second); err != nil { + t.Fatalf("docker didn't say hello: %v", err) + } +} + +func TestHttpd(t *testing.T) { + d := makeDocker("http-test") + + // Create temp directory to copy htdocs files. The sandbox doesn't have access + // to files in the test dir. + dir, err := ioutil.TempDir("", "httpd") + if err != nil { + t.Fatalf("ioutil.TempDir failed: %v", err) + } + if err := os.Chmod(dir, 0777); err != nil { + t.Fatalf("os.Chmod(%q, 0777) failed: %v", dir, err) + } + src := getLocalPath("latin10k.txt") + dst := path.Join(dir, "latin10k.txt") + if err := testutil.Copy(src, dst); err != nil { + t.Fatalf("testutil.Copy(%q, %q) failed: %v", src, dst, err) + } + + // Start the container. + if out, err := d.run("-p", "80", "-v", mountArg(dir, "/usr/local/apache2/htdocs"), "httpd"); err != nil { + t.Fatalf("docker run failed: %v\nout: %s", err, out) + } + defer d.cleanUp() + + // Find where port 80 is mapped to. + port, err := d.findPort(80) + if err != nil { + t.Fatalf("docker.findPort(80) failed: %v", err) + } + + // Wait until it's up and running. + if err := d.waitForOutput(".*'httpd -D FOREGROUND'.*", 5*time.Second); err != nil { + t.Fatalf("docker.WaitForOutput() timeout: %v", err) + } + + url := fmt.Sprintf("http://localhost:%d/not-found", port) + resp, err := http.Get(url) + if err != nil { + t.Fatalf("error reaching http server: %v", err) + } + if want := http.StatusNotFound; resp.StatusCode != want { + t.Errorf("Wrong response code, got: %d, want: %d", resp.StatusCode, want) + } + + url = fmt.Sprintf("http://localhost:%d/latin10k.txt", port) + resp, err = http.Get(url) + if err != nil { + t.Fatalf("Error reaching http server: %v", err) + } + if want := http.StatusOK; resp.StatusCode != want { + t.Errorf("Wrong response code, got: %d, want: %d", resp.StatusCode, want) + } + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + t.Fatalf("Error reading http response: %v", err) + } + defer resp.Body.Close() + + // READALL is the last word in the file. Ensures everything was read. + if want := "READALL"; strings.HasSuffix(string(body), want) { + t.Errorf("response doesn't contain %q, resp: %q", want, body) + } +} + +func MainTest(m *testing.M) { + // Check correct docker is installed. + cmd := exec.Command("docker", "version") + out, err := cmd.CombinedOutput() + if err != nil { + log.Fatalf("Error running %q: %v", "docker version", err) + } + re := regexp.MustCompile(`Version:\s+(\d+)\.(\d+)\.\d.*`) + matches := re.FindStringSubmatch(string(out)) + if len(matches) != 3 { + log.Fatalf("Invalid docker output: %s", out) + } + major, _ := strconv.Atoi(matches[1]) + minor, _ := strconv.Atoi(matches[2]) + if major < 17 || (major == 17 && minor < 9) { + log.Fatalf("Docker version 17.09.0 or greater is required, found: %02d.%02d", major, minor) + } + + os.Exit(m.Run()) +} diff --git a/runsc/test/image/latin10k.txt b/runsc/test/image/latin10k.txt new file mode 100644 index 000000000..61341e00b --- /dev/null +++ b/runsc/test/image/latin10k.txt @@ -0,0 +1,33 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras ut placerat felis. Maecenas urna est, auctor a efficitur sit amet, egestas et augue. Curabitur dignissim scelerisque nunc vel cursus. Ut vehicula est pretium, consectetur nunc non, pharetra ligula. Curabitur ut ultricies metus. Suspendisse pulvinar, orci sed fermentum vestibulum, eros turpis molestie lectus, nec elementum risus dolor mattis felis. Donec ultrices ipsum sem, at pretium lacus convallis at. Mauris nulla enim, tincidunt non bibendum at, vehicula pulvinar mauris. + +Duis in dapibus turpis. Pellentesque maximus magna odio, ac congue libero laoreet quis. Maecenas euismod risus in justo aliquam accumsan. Nunc quis ornare arcu, sit amet sodales elit. Phasellus nec scelerisque nisl, a tincidunt arcu. Proin ornare est nunc, sed suscipit orci interdum et. Suspendisse condimentum venenatis diam in tempor. Aliquam egestas lectus in rutrum tempus. Donec id egestas eros. Donec molestie consequat purus, sed posuere odio venenatis vitae. Nunc placerat augue id vehicula varius. In hac habitasse platea dictumst. Proin at est accumsan, venenatis quam a, fermentum risus. Phasellus posuere pellentesque enim, id suscipit magna consequat ut. Quisque ut tortor ante. + +Cras ut vulputate metus, a laoreet lectus. Vivamus ultrices molestie odio in tristique. Morbi faucibus mi eget sollicitudin fringilla. Fusce vitae lacinia ligula. Sed egestas sed diam eu posuere. Maecenas justo nisl, venenatis vel nibh vel, cursus aliquam velit. Praesent lacinia dui id erat venenatis rhoncus. Morbi gravida felis ante, sit amet vehicula orci rhoncus vitae. + +Sed finibus sagittis dictum. Proin auctor suscipit sem et mattis. Phasellus libero ligula, pellentesque ut felis porttitor, fermentum sollicitudin orci. Nulla eu nulla nibh. Fusce a eros risus. Proin vel magna risus. Donec nec elit eleifend, scelerisque sapien vitae, pharetra quam. Donec porttitor mauris scelerisque, tempus orci hendrerit, dapibus felis. Nullam libero elit, sollicitudin a aliquam at, ultrices in erat. Mauris eget ligula sodales, porta turpis et, scelerisque odio. Mauris mollis leo vitae purus gravida, in tempor nunc efficitur. Nulla facilisis posuere augue, nec pellentesque lectus eleifend ac. Vestibulum convallis est a feugiat tincidunt. Donec vitae enim volutpat, tincidunt eros eu, malesuada nibh. + +Quisque molestie, magna ornare elementum convallis, erat enim sagittis ipsum, eget porttitor sapien arcu id purus. Donec ut cursus diam. Nulla rutrum nulla et mi fermentum, vel tempus tellus posuere. Proin vitae pharetra nulla, nec ornare ex. Nulla consequat, augue a accumsan euismod, turpis leo ornare ligula, a pulvinar enim dolor ut augue. Quisque volutpat, lectus a varius mollis, nisl eros feugiat sem, at egestas lacus justo eu elit. Vestibulum scelerisque mauris est, sagittis interdum nunc accumsan sit amet. Maecenas aliquet ex ut lacus ornare, eu sagittis nibh imperdiet. Duis ultrices nisi velit, sed sodales risus sollicitudin et. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Etiam a accumsan augue, vitae pulvinar nulla. Pellentesque euismod sodales magna, nec luctus eros mattis eget. Sed lacinia suscipit lectus, eget consectetur dui pellentesque sed. Nullam nec mattis tellus. + +Aliquam erat volutpat. Praesent lobortis massa porttitor eros tincidunt, nec consequat diam pharetra. Duis efficitur non lorem sed mattis. Suspendisse justo nunc, pulvinar eu porttitor at, facilisis id eros. Suspendisse potenti. Cras molestie aliquet orci ut fermentum. In tempus aliquet eros nec suscipit. Suspendisse in mauris ut lectus ultrices blandit sit amet vitae est. Nam magna massa, porttitor ut semper id, feugiat vel quam. Suspendisse dignissim posuere scelerisque. Donec scelerisque lorem efficitur suscipit suscipit. Nunc luctus ligula et scelerisque lacinia. + +Suspendisse potenti. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed ultrices, sem in venenatis scelerisque, tellus ipsum porttitor urna, et iaculis lectus odio ac nisi. Integer luctus dui urna, at sollicitudin elit dapibus eu. Praesent nibh ante, porttitor a ante in, ullamcorper pretium felis. Aliquam vel tortor imperdiet, imperdiet lorem et, cursus mi. Proin tempus velit est, ut hendrerit metus gravida sed. Sed nibh sapien, faucibus quis ipsum in, scelerisque lacinia elit. In nec magna eu magna laoreet rhoncus. Donec vitae rutrum mauris. Integer urna felis, consequat at rhoncus vitae, auctor quis elit. Duis a pulvinar sem, nec gravida nisl. Nam non dapibus purus. Praesent vestibulum turpis nec erat porttitor, a scelerisque purus tincidunt. + +Nam fringilla leo nisi, nec placerat nisl luctus eget. Aenean malesuada nunc porta sapien sodales convallis. Suspendisse ut massa tempor, ullamcorper mi ut, faucibus turpis. Vivamus at sagittis metus. Donec varius ac mi eget sodales. Nulla feugiat, nulla eu fringilla fringilla, nunc lorem sollicitudin quam, vitae lacinia velit lorem eu orci. Mauris leo urna, pellentesque ac posuere non, pellentesque sit amet quam. + +Vestibulum porta diam urna, a aliquet nibh vestibulum et. Proin interdum bibendum nisl sed rhoncus. Sed vel diam hendrerit, faucibus ante et, hendrerit diam. Nunc dolor augue, mattis non dolor vel, luctus sodales neque. Cras malesuada fermentum dolor eu lobortis. Integer dapibus volutpat consequat. Maecenas posuere feugiat nunc. Donec vel mollis elit, volutpat consequat enim. Nulla id nisi finibus orci imperdiet elementum. Phasellus ultrices, elit vitae consequat rutrum, nisl est congue massa, quis condimentum justo nisi vitae turpis. Maecenas aliquet risus sit amet accumsan elementum. Proin non finibus elit, sit amet lobortis augue. + +Morbi pretium pulvinar sem vel sollicitudin. Proin imperdiet fringilla leo, non pellentesque lacus gravida nec. Vivamus ullamcorper consectetur ligula eu consectetur. Curabitur sit amet tempus purus. Curabitur quam quam, tincidunt eu tempus vel, volutpat at ipsum. Maecenas lobortis elit ac justo interdum, sit amet mattis ligula mollis. Sed posuere ligula et felis convallis tempor. Aliquam nec mollis velit. Donec varius sit amet erat at imperdiet. Nulla ipsum justo, tempor non sollicitudin gravida, dignissim vel orci. In hac habitasse platea dictumst. Cras cursus tellus id arcu aliquet accumsan. Phasellus ac erat dui. + +Duis mollis metus at mi luctus aliquam. Duis varius eget erat ac porttitor. Phasellus lobortis sagittis lacinia. Etiam sagittis eget erat in pulvinar. Phasellus sodales risus nec vulputate accumsan. Cras sit amet pellentesque dui. Praesent consequat felis mi, at vulputate diam convallis a. Donec hendrerit nibh vel justo consequat dictum. In euismod, dui sit amet malesuada suscipit, mauris ex rhoncus eros, sed ornare arcu nunc eu urna. Pellentesque eget erat augue. Integer rutrum mauris sem, nec sodales nulla cursus vel. Vivamus porta, urna vel varius vulputate, nulla arcu malesuada dui, a ultrices magna ante sed nibh. + +Morbi ultricies aliquam lorem id bibendum. Donec sit amet nunc vitae massa gravida eleifend hendrerit vel libero. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla vestibulum tempus condimentum. Aliquam dolor ipsum, condimentum in sapien et, tempor iaculis nulla. Aenean non pharetra augue. Maecenas mattis dignissim maximus. Fusce elementum tincidunt massa sit amet lobortis. Phasellus nec pharetra dui, et malesuada ante. Nullam commodo pretium tellus. Praesent sollicitudin, enim eget imperdiet scelerisque, odio felis vulputate dolor, eget auctor neque tellus ac lorem. + +In consectetur augue et sapien feugiat varius. Nam tortor mi, consectetur ac felis non, elementum venenatis augue. Suspendisse ut tellus in est sagittis cursus. Quisque faucibus, neque sit amet semper congue, nibh augue finibus odio, vitae interdum dolor arcu eget arcu. Curabitur dictum risus massa, non tincidunt urna molestie non. Maecenas eu quam purus. Donec vulputate, dui eu accumsan blandit, mauris tortor tristique mi, sed blandit leo quam id quam. Ut venenatis sagittis malesuada. Integer non auctor orci. Duis consectetur massa felis. Fusce euismod est sit amet bibendum finibus. Vestibulum dolor ex, tempor at elit in, iaculis cursus dui. Nunc sed neque ac risus rutrum tempus sit amet at ante. In hac habitasse platea dictumst. + +Donec rutrum, velit nec viverra tincidunt, est velit viverra neque, quis auctor leo ex at lectus. Morbi eget purus nisi. Aliquam lacus dui, interdum vitae elit at, venenatis dignissim est. Duis ac mollis lorem. Vivamus a vestibulum quam. Maecenas non metus dolor. Praesent tortor nunc, tristique at nisl molestie, vulputate eleifend diam. Integer ultrices lacus odio, vel imperdiet enim accumsan id. Sed ligula tortor, interdum eu velit eget, pharetra pulvinar magna. Sed non lacus in eros tincidunt sagittis ac vel justo. Donec vitae leo sagittis, accumsan ante sit amet, accumsan odio. Ut volutpat ultricies tortor. Vestibulum tempus purus et est tristique sagittis quis vitae turpis. + +Nam iaculis neque lacus, eget euismod turpis blandit eget. In hac habitasse platea dictumst. Phasellus justo neque, scelerisque sit amet risus ut, pretium commodo nisl. Phasellus auctor sapien sed ex bibendum fermentum. Proin maximus odio a ante ornare, a feugiat lorem egestas. Etiam efficitur tortor a ante tincidunt interdum. Nullam non est ac massa congue efficitur sit amet nec eros. Nullam at ipsum vel mauris tincidunt efficitur. Duis pulvinar nisl elit, id auctor risus laoreet ac. Sed nunc mauris, tristique id leo ut, condimentum congue nunc. Sed ultricies, mauris et convallis faucibus, justo ex faucibus est, at lobortis purus justo non arcu. Integer vel facilisis elit, dapibus imperdiet mauris. + +Pellentesque non mattis turpis, eget bibendum velit. Fusce sollicitudin ante ac tincidunt rhoncus. Praesent porta scelerisque consequat. Donec eleifend faucibus sollicitudin. Quisque vitae purus eget tortor tempor ultrices. Maecenas mauris diam, semper vitae est non, imperdiet tempor magna. Duis elit lacus, auctor vestibulum enim eget, rhoncus porttitor tortor. + +Donec non rhoncus nibh. Cras dapibus justo vitae nunc accumsan, id congue erat egestas. Aenean at ante ante. Duis eleifend imperdiet dREADALL diff --git a/runsc/test/testutil/testutil.go b/runsc/test/testutil/testutil.go index 9be4407e0..25535ea37 100644 --- a/runsc/test/testutil/testutil.go +++ b/runsc/test/testutil/testutil.go @@ -18,6 +18,7 @@ package testutil import ( "encoding/json" "fmt" + "io" "io/ioutil" "os" "path/filepath" @@ -146,3 +147,21 @@ func writeSpec(dir string, spec *specs.Spec) error { func UniqueContainerID() string { return fmt.Sprintf("test-container-%d", time.Now().UnixNano()) } + +// Copy copies file from src to dst. +func Copy(src, dst string) error { + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + + out, err := os.Create(dst) + if err != nil { + return err + } + defer out.Close() + + _, err = io.Copy(out, in) + return err +} |