func TestMountRequest(t *testing.T) {
	StartTest(t)
	defer FinishTest(t)
	TestRequiresRoot(t)

	// Start the initd process.
	_, socket, _, pid := StartInitd(t)

	content := uuid.Variant4().String()

	tempDir, err := ioutil.TempDir("/var", "container"+uuid.Variant4().String())
	TestExpectSuccess(t, err)
	AddTestFinalizer(func() { os.RemoveAll(tempDir) })
	err = os.Chmod(tempDir, os.FileMode(0755))
	TestExpectSuccess(t, err)
	TestExpectSuccess(t, ioutil.WriteFile(filepath.Join(tempDir, "foo"), []byte(content), os.FileMode(0644)))

	otherTempDir, err := ioutil.TempDir("/var", "container"+uuid.Variant4().String())
	TestExpectSuccess(t, err)
	AddTestFinalizer(func() { os.RemoveAll(otherTempDir) })

	request := [][]string{
		[]string{"MOUNT", tempDir, otherTempDir},
		[]string{"", fmt.Sprintf("%d", syscall.MS_BIND), ""},
	}
	reply, err := MakeRequest(socket, request, 10*time.Second)
	TestExpectSuccess(t, err)
	TestEqual(t, reply, "REQUEST OK\n")

	// Next check to see that the init daemon is mounted the path correctly.
	contents, err := ioutil.ReadFile(filepath.Join(fmt.Sprintf("/proc/%d/root", pid), otherTempDir, "foo"))
	TestExpectSuccess(t, err)
	TestEqual(t, string(contents), content)
}
Exemple #2
0
func (s *rpcServer) Create(ctx context.Context, in *pb.CreateRequest) (*pb.CreateResponse, error) {
	s.log.Debug("Received Create request.")

	// unmarshal the image manifest, ensure its valid
	var imageManifest *schema.ImageManifest
	if err := json.Unmarshal(in.Manifest, &imageManifest); err != nil {
		return nil, fmt.Errorf("invalid image manifest: %v", err)
	}

	// validate the manifest with the manager
	if err := s.manager.Validate(imageManifest); err != nil {
		return nil, fmt.Errorf("image manifest is not valid: %v", err)
	}

	// put together the pending container handler
	pc := &pendingContainer{
		name:          in.Name,
		imageManifest: imageManifest,
	}
	resp := &pb.CreateResponse{
		ImageUploadId: uuid.Variant4().String(),
	}
	s.pendingUploads[resp.ImageUploadId] = pc

	s.log.Debug("Finished Create request.")
	return resp, nil
}
Exemple #3
0
func MakeUniqueCgroup(t *testing.T) (string, *Cgroup) {
	uniquename := fmt.Sprintf("unittest-%s", uuid.Variant4().String())
	cgroup, err := New(uniquename)
	if err != nil {
		Fatalf(t, "Unexpected error: %s", err)
	}
	return uniquename, cgroup
}
Exemple #4
0
// Documents a simple use case for a generating and comparing UUIDs.
func Example() {
	u1 := uuid.Variant1()
	u2 := uuid.Variant4()
	fmt.Println("Text representation of a uuid: ", u1.String())
	if u1.Equal(u2) {
		fmt.Println("UUIDs shouldn't ever be equal so this is not reached.")
	}
}
Exemple #5
0
// Makes a common cgroup and ensures that it gets destroyed on test exit.
func makeCgroup(t *testing.T) *cgroups.Cgroup {
	name := fmt.Sprintf("unittesting-%s", uuid.Variant4().String())
	cgroup, err := cgroups.New(name)
	TestExpectSuccess(t, err)
	AddTestFinalizer(func() {
		TestExpectSuccess(t, cgroup.Destroy())
	})
	return cgroup
}
Exemple #6
0
// Tests that Variant4() will not produce duplicate UUIDs. This is actually not
// assured by the protocol given that its 125 bits of random numbers. Still,
// the likely hood of duplicating in a few thousand tries should be low enough
// 2^125 / 1000
func TestVariant4(t *testing.T) {
	previous := make(map[string]bool)

	for i := 0; i < 10000; i++ {
		u := uuid.Variant4().String()
		if _, exists := previous[u]; exists == true {
			t.Fatal("Duplicate UUIDs generated from Variant4(): ", u)
		}
		previous[u] = true
	}
}
Exemple #7
0
// Create begins launching a container with the provided image manifest and
// reader as the source of the ACI.
func (manager *Manager) Create(
	name string, imageManifest *schema.ImageManifest, image io.ReadCloser,
) (*Container, error) {
	// revalidate the image
	if err := manager.Validate(imageManifest); err != nil {
		return nil, err
	}

	// handle a blank name
	if name == "" {
		name = imageManifest.Name.String()
	}

	// populate the container
	container := &Container{
		manager:          manager,
		log:              manager.Log.Clone(),
		uuid:             uuid.Variant4().String(),
		waitch:           make(chan bool),
		initialImageFile: image,
		image:            imageManifest,
		pod: &schema.PodManifest{
			ACKind:    schema.PodManifestKind,
			ACVersion: schema.AppContainerVersion,
			Apps: schema.AppList([]schema.RuntimeApp{
				schema.RuntimeApp{
					Name: types.ACName(name),
					App:  imageManifest.App,
					Image: schema.RuntimeImage{
						Name:   &imageManifest.Name,
						Labels: imageManifest.Labels,
					},
				},
			}),
		},
	}
	container.log.SetField("container", container.uuid)
	container.log.Debugf("Launching container %s", container.uuid)

	// add it to the manager's map
	manager.containersLock.Lock()
	manager.containers[container.uuid] = container
	manager.containersLock.Unlock()

	// begin the startup sequence
	container.start()

	return container, nil
}
func TestChrootRequest(t *testing.T) {
	StartTest(t)
	defer FinishTest(t)
	TestRequiresRoot(t)

	// Start the initd process.
	_, socket, _, _ := StartInitd(t)

	chrootDir, err := ioutil.TempDir("/var", "container"+uuid.Variant4().String())
	TestExpectSuccess(t, err)
	AddTestFinalizer(func() { os.RemoveAll(chrootDir) })
	err = os.Chmod(chrootDir, os.FileMode(0755))
	TestExpectSuccess(t, err)

	request := [][]string{[]string{"CHROOT", chrootDir}}
	reply, err := MakeRequest(socket, request, 10*time.Second)
	TestExpectSuccess(t, err)
	TestEqual(t, reply, "REQUEST OK\n")
}
Exemple #9
0
func TestNew(t *testing.T) {
	StartTest(t)
	defer FinishTest(t)
	TestRequiresRoot(t)

	// ------------------
	// Failure Conditions
	// ------------------

	// Test 1: Tasks is not autopopulated
	func() {
		defer func(c string) { cgroupsDir = c }(cgroupsDir)
		cgroupsDir = TempDir(t)
		if _, err := New("test"); err == nil {
			Fatalf(t, "Expected error not returned.")
		}
	}()

	// Test 2: Cgroup already exists.
	func() {
		defer func(c string) { cgroupsDir = c }(cgroupsDir)
		cgroupsDir = TempDir(t)
		fn := path.Join(cgroupsDir, defaultCgroups[0], "test")
		if err := os.MkdirAll(fn, 0755); err != nil {
			Fatalf(t, "Unexpected error: %s", err)
		}
		if _, err := New("test"); err == nil {
			Fatalf(t, "Expected error not returned.")
		}
	}()

	// Test 3: Cgroup directory is actually a file.
	func() {
		defer func(c string) { cgroupsDir = c }(cgroupsDir)
		cgroupsDir = TempDir(t)
		fn := path.Join(cgroupsDir, defaultCgroups[0])
		if err := os.MkdirAll(fn, 0755); err != nil {
			Fatalf(t, "Unexpected error: %s", err)
		}
		fn = path.Join(cgroupsDir, defaultCgroups[0], "test")
		if err := ioutil.WriteFile(fn, []byte{}, 0644); err != nil {
			Fatalf(t, "Unexpected error: %s", err)
		}
		if _, err := New("test"); err == nil {
			Fatalf(t, "Expected error not returned.")
		}
	}()

	// Test 4: Make the directory creation fail.
	func() {
		defer func(c string) { cgroupsDir = c }(cgroupsDir)
		defer func() { osMkdir = os.Mkdir }()
		osMkdir = func(name string, mode os.FileMode) error {
			return fmt.Errorf("expected error from Mkdir()")
		}

		cgroupsDir = TempDir(t)
		fn := path.Join(cgroupsDir, defaultCgroups[0])
		if err := os.MkdirAll(fn, 0755); err != nil {
			Fatalf(t, "Unexpected error: %s", err)
		}
		if _, err := New("test"); err == nil {
			Fatalf(t, "Expected error not returned.")
		}
	}()

	// Test 5: Make the directory stat fail.
	func() {
		defer func(c string) { cgroupsDir = c }(cgroupsDir)
		defer func() { osLstat = os.Lstat }()
		osLstat = func(name string) (os.FileInfo, error) {
			return nil, fmt.Errorf("expected error from os.Lstat()")
		}

		cgroupsDir = TempDir(t)
		fn := path.Join(cgroupsDir, defaultCgroups[0])
		if err := os.MkdirAll(fn, 0755); err != nil {
			Fatalf(t, "Unexpected error: %s", err)
		}
		if _, err := New("test"); err == nil {
			Fatalf(t, "Expected error not returned.")
		}
	}()

	// Test 6: Existing tasks in the cgroup.
	func() {
		// A unique name to use for cgroup names.
		uniquename := fmt.Sprintf("unittest-%s", uuid.Variant4().String())

		cgroup := path.Join(cgroupsDir, "memory", uniquename)

		// Ensure that we remove this cgroups when the test finishes.
		defer func() {
			// We loop to see if we can remove this for 5 seconds.
			end := time.Now().Add(time.Second * 5)
			for time.Now().Before(end) {
				if err := os.Remove(cgroup); err == nil {
					return
				}
				time.Sleep(time.Millisecond * 100)
			}
			Fatalf(t, "Error removing cgroups directory.")
		}()

		if err := os.Mkdir(cgroup, 0755); err != nil {
			if !os.IsExist(err) {
				Fatalf(t, "Unexpected error: %s", err)
			}
		}

		// Put a signal watcher in the cgroup.
		cmd, fd := StartSignalWatcher(t, cgroup)

		// Kill the process we created so the test cleans up properly.
		defer func() {
			// Kill the child process.
			if err := cmd.Process.Signal(syscall.SIGKILL); err != nil {
				t.Errorf("Error killing the child: %s", err)
			}
			// Read from the stdout for the process until it dies.
			if _, err := ioutil.ReadAll(fd); err != nil {
				t.Errorf("Error waiting for child to die: %s", err)
			}
		}()

		// Now attempt to create the cgroup which should fail because it already has
		// tasks in it.
		if _, err := New(uniquename); err == nil {
			Fatalf(t, "Expected error not returned.")
		}
	}()

	// -------
	// Success
	// -------

	// A unique name to use for cgroup names.
	_, cgroup := MakeUniqueCgroup(t)
	defer CleanupCgroup(t, cgroup)
}
Exemple #10
0
// Benchmarks the Variant4() UUIDs.
func BenchmarkVariant4(b *testing.B) {
	for i := 0; i < b.N; i++ {
		uuid.Variant4()
	}
}