func TestHandlerPatchItemReplaceInvalidModifiedSinceDate(t *testing.T) {
	index := resource.NewIndex()
	s := mem.NewHandler()
	now := time.Now()
	s.Insert(context.TODO(), []*resource.Item{
		{ID: "1", Updated: now, Payload: map[string]interface{}{"id": "1"}},
	})
	test := index.Bind("test", schema.Schema{Fields: schema.Fields{"id": {}}}, s, resource.DefaultConf)
	r, _ := http.NewRequest("PATCH", "/test/1", bytes.NewBufferString(`{"id": "1"}`))
	r.Header.Set("If-Unmodified-Since", "invalid date")
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "test",
				Field:    "id",
				Value:    "1",
				Resource: test,
			},
		},
	}
	status, _, body := itemPatch(context.TODO(), r, rm)
	assert.Equal(t, http.StatusBadRequest, status)
	if assert.IsType(t, body, &Error{}) {
		err := body.(*Error)
		assert.Equal(t, http.StatusBadRequest, err.Code)
		assert.Equal(t, "Invalid If-Unmodified-Since header", err.Message)
	}
}
func TestHandlerPatchItemCannotChangeID(t *testing.T) {
	index := resource.NewIndex()
	s := mem.NewHandler()
	s.Insert(context.TODO(), []*resource.Item{
		{ID: "1", Payload: map[string]interface{}{"id": "1"}},
	})
	test := index.Bind("test", schema.Schema{Fields: schema.Fields{"id": {}}}, s, resource.DefaultConf)
	r, _ := http.NewRequest("PATCH", "/test/1", bytes.NewBufferString(`{"id": "2"}`))
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "test",
				Field:    "id",
				Value:    "1",
				Resource: test,
			},
		},
	}
	status, headers, body := itemPatch(context.TODO(), r, rm)
	assert.Equal(t, 422, status)
	assert.Nil(t, headers)
	if assert.IsType(t, body, &Error{}) {
		err := body.(*Error)
		assert.Equal(t, 422, err.Code)
		assert.Equal(t, "Cannot change document ID", err.Message)
	}
}
Beispiel #3
0
func TestNewWorkerPool(t *testing.T) {
	var count int64

	fn := func() {
		atomic.AddInt64(&count, 1)
	}

	p := concurrency.NewWorkerPool(context.TODO(), concurrency.Config{
		CloseTimeout: time.Millisecond * 200,
		Capacity:     16,
	})
	err := p.Open()
	assert.NoError(t, err)

	wg := &sync.WaitGroup{}
	for i := 0; i < 100; i++ {
		wg.Add(1)
		err = p.Execute(context.TODO(), func() {
			defer wg.Done()
			fn()
		})
	}

	wg.Wait()

	err = p.Close()
	assert.NoError(t, err)

	err = p.Wait()
	assert.NoError(t, err)

	assert.EqualValues(t, 100, count)

}
func TestHandlerPatchItemFound(t *testing.T) {
	index := resource.NewIndex()
	s := mem.NewHandler()
	s.Insert(context.TODO(), []*resource.Item{
		{ID: "1", Payload: map[string]interface{}{"id": "1", "foo": "bar"}},
		{ID: "2", Payload: map[string]interface{}{"id": "2", "foo": "bar"}},
		{ID: "3", Payload: map[string]interface{}{"id": "3", "foo": "bar"}},
	})
	test := index.Bind("test", schema.Schema{Fields: schema.Fields{
		"id":  {},
		"foo": {},
	}}, s, resource.DefaultConf)
	r, _ := http.NewRequest("PATCH", "/test/2", bytes.NewBufferString(`{"id": "2", "foo": "baz"}`))
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "test",
				Field:    "id",
				Value:    "2",
				Resource: test,
			},
		},
	}
	status, headers, body := itemPatch(context.TODO(), r, rm)
	assert.Equal(t, http.StatusOK, status)
	assert.Nil(t, headers)
	if assert.IsType(t, body, &resource.Item{}) {
		i := body.(*resource.Item)
		assert.Equal(t, "2", i.ID)
		assert.Equal(t, map[string]interface{}{"id": "2", "foo": "baz"}, i.Payload)
	}
}
Beispiel #5
0
func TestHandlerPutItemReplaceModeNotAllowed(t *testing.T) {
	index := resource.NewIndex()
	s := mem.NewHandler()
	s.Insert(context.TODO(), []*resource.Item{
		{ID: "1", Payload: map[string]interface{}{"id": "1"}},
	})
	test := index.Bind("test", schema.Schema{Fields: schema.Fields{"id": {}}}, s, resource.Conf{
		AllowedModes: []resource.Mode{resource.Create},
	})
	r, _ := http.NewRequest("PUT", "/test/1", bytes.NewBufferString(`{}`))
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "test",
				Field:    "id",
				Value:    "1",
				Resource: test,
			},
		},
	}
	status, headers, body := itemPut(context.TODO(), r, rm)
	assert.Equal(t, http.StatusMethodNotAllowed, status)
	assert.Nil(t, headers)
	if assert.IsType(t, body, &Error{}) {
		err := body.(*Error)
		assert.Equal(t, http.StatusMethodNotAllowed, err.Code)
		assert.Equal(t, "Invalid method", err.Message)
	}
}
Beispiel #6
0
func TestAlertingExecutor(t *testing.T) {
	Convey("Test alert execution", t, func() {
		handler := NewEvalHandler()

		Convey("Show return triggered with single passing condition", func() {
			context := NewEvalContext(context.TODO(), &Rule{
				Conditions: []Condition{&conditionStub{
					firing: true,
				}},
			})

			handler.Eval(context)
			So(context.Firing, ShouldEqual, true)
		})

		Convey("Show return false with not passing asdf", func() {
			context := NewEvalContext(context.TODO(), &Rule{
				Conditions: []Condition{
					&conditionStub{firing: true, matches: []*EvalMatch{&EvalMatch{}, &EvalMatch{}}},
					&conditionStub{firing: false},
				},
			})

			handler.Eval(context)
			So(context.Firing, ShouldEqual, false)
		})
	})
}
Beispiel #7
0
func TestHandlerGetItem(t *testing.T) {
	s := mem.NewHandler()
	s.Insert(context.TODO(), []*resource.Item{
		{ID: "1", Payload: map[string]interface{}{"id": "1"}},
		{ID: "2", Payload: map[string]interface{}{"id": "2"}},
		{ID: "3", Payload: map[string]interface{}{"id": "3"}},
	})
	index := resource.NewIndex()
	test := index.Bind("test", schema.Schema{}, s, resource.DefaultConf)
	r, _ := http.NewRequest("GET", "/test/2", nil)
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "test",
				Field:    "id",
				Value:    "2",
				Resource: test,
			},
		},
	}
	status, headers, body := itemGet(context.TODO(), r, rm)
	assert.Equal(t, http.StatusOK, status)
	assert.Nil(t, headers)
	if assert.IsType(t, body, &resource.Item{}) {
		i := body.(*resource.Item)
		assert.Equal(t, "2", i.ID)
	}
}
func TestHandlerDeleteItemEtag(t *testing.T) {
	s := mem.NewHandler()
	s.Insert(context.TODO(), []*resource.Item{
		{ID: "1", ETag: "a", Payload: map[string]interface{}{"id": "1"}},
	})
	index := resource.NewIndex()
	test := index.Bind("test", schema.Schema{
		Fields: schema.Fields{"foo": {Filterable: true}},
	}, s, resource.DefaultConf)
	r, _ := http.NewRequest("DELETE", "/test/2", nil)
	r.Header.Set("If-Match", "a")
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "test",
				Field:    "id",
				Value:    "1",
				Resource: test,
			},
		},
	}
	status, headers, body := itemDelete(context.TODO(), r, rm)
	assert.Equal(t, http.StatusNoContent, status)
	assert.Nil(t, headers)
	assert.Nil(t, body)

	l, err := s.Find(context.TODO(), resource.NewLookup(), 1, -1)
	assert.NoError(t, err)
	assert.Len(t, l.Items, 0)
}
Beispiel #9
0
func TestHandlerGetItemModifiedDontMatch(t *testing.T) {
	s := mem.NewHandler()
	now := time.Now()
	yesterday := now.Add(-24 * time.Hour)
	s.Insert(context.TODO(), []*resource.Item{
		{ID: "1", Updated: now, Payload: map[string]interface{}{"id": "1"}},
		{ID: "2", Updated: now, Payload: map[string]interface{}{"id": "2"}},
		{ID: "3", Updated: now, Payload: map[string]interface{}{"id": "3"}},
	})
	index := resource.NewIndex()
	test := index.Bind("test", schema.Schema{}, s, resource.DefaultConf)
	r, _ := http.NewRequest("GET", "/test/2", nil)
	r.Header.Set("If-Modified-Since", yesterday.Format(time.RFC1123))
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "test",
				Field:    "id",
				Value:    "2",
				Resource: test,
			},
		},
	}
	status, headers, body := itemGet(context.TODO(), r, rm)
	assert.Equal(t, http.StatusOK, status)
	assert.Nil(t, headers)
	if assert.IsType(t, body, &resource.Item{}) {
		i := body.(*resource.Item)
		assert.Equal(t, "2", i.ID)
	}
}
Beispiel #10
0
func TestHandlerGetItemInvalidIfModifiedSince(t *testing.T) {
	s := mem.NewHandler()
	now := time.Now()
	s.Insert(context.TODO(), []*resource.Item{
		{ID: "1", Updated: now, Payload: map[string]interface{}{"id": "1"}},
		{ID: "2", Updated: now, Payload: map[string]interface{}{"id": "2"}},
		{ID: "3", Updated: now, Payload: map[string]interface{}{"id": "3"}},
	})
	index := resource.NewIndex()
	test := index.Bind("test", schema.Schema{}, s, resource.DefaultConf)
	r, _ := http.NewRequest("GET", "/test/2", nil)
	r.Header.Set("If-Modified-Since", "invalid date")
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "test",
				Field:    "id",
				Value:    "2",
				Resource: test,
			},
		},
	}
	status, headers, body := itemGet(context.TODO(), r, rm)
	assert.Equal(t, http.StatusBadRequest, status)
	assert.Nil(t, headers)
	if assert.IsType(t, body, &Error{}) {
		err := body.(*Error)
		assert.Equal(t, http.StatusBadRequest, err.Code)
		assert.Equal(t, "Invalid If-Modified-Since header", err.Message)
	}
}
Beispiel #11
0
func TestHandlerGetItemEtagMatch(t *testing.T) {
	s := mem.NewHandler()
	s.Insert(context.TODO(), []*resource.Item{
		{ID: "1", ETag: "a", Payload: map[string]interface{}{"id": "1"}},
		{ID: "2", ETag: "a", Payload: map[string]interface{}{"id": "2"}},
		{ID: "3", ETag: "a", Payload: map[string]interface{}{"id": "3"}},
	})
	index := resource.NewIndex()
	test := index.Bind("test", schema.Schema{}, s, resource.DefaultConf)
	r, _ := http.NewRequest("GET", "/test/2", nil)
	r.Header.Set("If-None-Match", "a")
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "test",
				Field:    "id",
				Value:    "2",
				Resource: test,
			},
		},
	}
	status, headers, body := itemGet(context.TODO(), r, rm)
	assert.Equal(t, http.StatusNotModified, status)
	assert.Nil(t, headers)
	assert.Nil(t, body)
}
Beispiel #12
0
func TestGitHubClient_Upload(t *testing.T) {
	client := testGithubClient(t)
	testTag := "github-client-upload-asset"
	req := &github.RepositoryRelease{
		TagName: github.String(testTag),
		Draft:   github.Bool(true),
	}

	release, err := client.CreateRelease(context.TODO(), req)
	if err != nil {
		t.Fatal("CreateRelease failed:", err)
	}

	defer func() {
		if err := client.DeleteRelease(context.TODO(), *release.ID); err != nil {
			t.Fatalf("DeleteRelease failed: %s", err)
		}
	}()

	filename := filepath.Join("./testdata", "darwin_386")
	asset, err := client.UploadAsset(context.TODO(), *release.ID, filename)
	if err != nil {
		t.Fatal("UploadAsset failed:", err)
	}

	githubClient, ok := client.(*GitHubClient)
	if !ok {
		t.Fatal("Faield to asset to GithubClient")
	}

	rc, url, err := githubClient.Repositories.DownloadReleaseAsset(
		githubClient.Owner, githubClient.Repo, *asset.ID)
	if err != nil {
		t.Fatal("DownloadReleaseAsset failed:", err)
	}

	var buf bytes.Buffer
	if len(url) != 0 {
		res, err := http.Get(url)
		if err != nil {
			t.Fatal("http.Get failed:", err)
		}

		if _, err := io.Copy(&buf, res.Body); err != nil {
			t.Fatal("Copy failed:", err)
		}
		res.Body.Close()

	} else {
		if _, err := io.Copy(&buf, rc); err != nil {
			t.Fatal("Copy failed:", err)
		}
		rc.Close()

	}

	if got, want := buf.String(), "darwin_386\n"; got != want {
		t.Fatalf("file body is %q, want %q", got, want)
	}
}
Beispiel #13
0
func TestHandlerGetListInvalidPage(t *testing.T) {
	index := resource.NewIndex()
	test := index.Bind("test", schema.Schema{}, nil, resource.DefaultConf)
	r, _ := http.NewRequest("GET", "/test", nil)
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "test",
				Resource: test,
			},
		},
		Params: url.Values{
			"page": []string{"invalid"},
		},
	}
	status, headers, body := listGet(context.TODO(), r, rm)
	assert.Equal(t, 422, status)
	assert.Nil(t, headers)
	if assert.IsType(t, body, &Error{}) {
		err := body.(*Error)
		assert.Equal(t, 422, err.Code)
		assert.Equal(t, "Invalid `page` parameter", err.Message)
	}

	rm.Params.Set("page", "-1")

	status, headers, body = listGet(context.TODO(), r, rm)
	assert.Equal(t, 422, status)
	assert.Nil(t, headers)
	if assert.IsType(t, body, &Error{}) {
		err := body.(*Error)
		assert.Equal(t, 422, err.Code)
		assert.Equal(t, "Invalid `page` parameter", err.Message)
	}
}
Beispiel #14
0
func TestHandlerDeleteList(t *testing.T) {
	s := mem.NewHandler()
	s.Insert(context.TODO(), []*resource.Item{
		{ID: "1", Payload: map[string]interface{}{}},
		{ID: "2", Payload: map[string]interface{}{}},
		{ID: "3", Payload: map[string]interface{}{}},
		{ID: "4", Payload: map[string]interface{}{}},
		{ID: "5", Payload: map[string]interface{}{}},
	})
	index := resource.NewIndex()
	test := index.Bind("test", schema.Schema{}, s, resource.DefaultConf)
	r, _ := http.NewRequest("DELETE", "/test", bytes.NewBufferString("{}"))
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "test",
				Resource: test,
			},
		},
	}
	status, headers, body := listDelete(context.TODO(), r, rm)
	assert.Equal(t, http.StatusNoContent, status)
	assert.Equal(t, http.Header{"X-Total": []string{"5"}}, headers)
	assert.Nil(t, body)

	l, err := s.Find(context.TODO(), resource.NewLookup(), 1, -1)
	assert.NoError(t, err)
	assert.Len(t, l.Items, 0)
}
Beispiel #15
0
func TestHandlerGetListPagination(t *testing.T) {
	s := mem.NewHandler()
	s.Insert(context.TODO(), []*resource.Item{
		{ID: "1"},
		{ID: "2"},
		{ID: "3"},
		{ID: "4"},
		{ID: "5"},
	})
	index := resource.NewIndex()
	test := index.Bind("test", schema.Schema{}, s, resource.DefaultConf)
	r, _ := http.NewRequest("GET", "/test", nil)
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "test",
				Resource: test,
			},
		},
		Params: url.Values{
			"page":  []string{"2"},
			"limit": []string{"2"},
		},
	}
	status, headers, body := listGet(context.TODO(), r, rm)
	assert.Equal(t, http.StatusOK, status)
	assert.Nil(t, headers)
	if assert.IsType(t, body, &resource.ItemList{}) {
		l := body.(*resource.ItemList)
		if assert.Len(t, l.Items, 2) {
			assert.Equal(t, "3", l.Items[0].ID)
			assert.Equal(t, "4", l.Items[1].ID)
		}
		assert.Equal(t, 2, l.Page)
		assert.Equal(t, 5, l.Total)
	}

	rm.Params.Set("page", "3")

	status, headers, body = listGet(context.TODO(), r, rm)
	assert.Equal(t, http.StatusOK, status)
	assert.Nil(t, headers)
	if assert.IsType(t, body, &resource.ItemList{}) {
		l := body.(*resource.ItemList)
		if assert.Len(t, l.Items, 1) {
			assert.Equal(t, "5", l.Items[0].ID)
		}
		assert.Equal(t, 3, l.Page)
		assert.Equal(t, 5, l.Total)
	}
}
Beispiel #16
0
func (ids *IDService) IdentifyConn(c inet.Conn) {
	ids.currmu.Lock()
	if wait, found := ids.currid[c]; found {
		ids.currmu.Unlock()
		log.Debugf("IdentifyConn called twice on: %s", c)
		<-wait // already identifying it. wait for it.
		return
	}
	ch := make(chan struct{})
	ids.currid[c] = ch
	ids.currmu.Unlock()

	defer close(ch)

	s, err := c.NewStream()
	if err != nil {
		log.Debugf("error opening initial stream for %s: %s", ID, err)
		log.Event(context.TODO(), "IdentifyOpenFailed", c.RemotePeer())
		c.Close()
		return
	}
	defer s.Close()

	s.SetProtocol(ID)

	if ids.Reporter != nil {
		s = mstream.WrapStream(s, ids.Reporter)
	}

	// ok give the response to our handler.
	if err := msmux.SelectProtoOrFail(ID, s); err != nil {
		log.Debugf("error writing stream header for %s", ID)
		log.Event(context.TODO(), "IdentifyOpenFailed", c.RemotePeer())
		return
	}

	ids.ResponseHandler(s)

	ids.currmu.Lock()
	_, found := ids.currid[c]
	delete(ids.currid, c)
	ids.currmu.Unlock()

	if !found {
		log.Debugf("IdentifyConn failed to find channel (programmer error) for %s", c)
		return
	}
}
Beispiel #17
0
func TestRun(t *testing.T) {
	t.Parallel()

	outStream, errStream := new(bytes.Buffer), new(bytes.Buffer)
	cli := &CLI{outStream: outStream, errStream: errStream}

	tag := "run"
	command := fmt.Sprintf(
		"ghr -repository %s %s %s", TestRepo, tag, TestDir)

	args := strings.Split(command, " ")
	if got, want := cli.Run(args), ExitCodeOK; got != want {
		t.Fatalf("%q exits %d, want %d\n\n%s", command, got, want, errStream.String())
	}

	client := testGithubClient(t)
	release, err := client.GetRelease(context.TODO(), tag)
	if err != nil {
		t.Fatalf("GetRelease failed: %s\n\n%s", err, outStream.String())
	}
	defer func() {
		if err := client.DeleteRelease(context.TODO(), *release.ID); err != nil {
			t.Fatal("DeleteRelease failed:", err)
		}

		if err := client.DeleteTag(context.TODO(), tag); err != nil {
			t.Fatal("DeleteTag failed:", err)
		}
	}()

	want := "==> Create a new release"
	if got := outStream.String(); !strings.Contains(got, want) {
		t.Fatalf("Run outputs %q, want %q", got, want)
	}

	if got, want := outStream.String(), "--> Uploading:"; !strings.Contains(got, want) {
		t.Fatalf("Run outputs %q, want %q", got, want)
	}

	assets, err := client.ListAssets(context.TODO(), *release.ID)
	if err != nil {
		t.Fatal("ListAssets failed:", err)
	}

	if got, want := len(assets), 4; got != want {
		t.Fatalf("ListAssets number = %d, want %d", got, want)
	}
}
Beispiel #18
0
Datei: ls.go Projekt: vmware/vic
func (cmd *ls) ListPath(b *object.HostDatastoreBrowser, path string, spec types.HostDatastoreBrowserSearchSpec) ([]types.HostDatastoreBrowserSearchResults, error) {
	ctx := context.TODO()

	path, err := cmd.DatastorePath(path)
	if err != nil {
		return nil, err
	}

	search := b.SearchDatastore
	if cmd.recurse {
		search = b.SearchDatastoreSubFolders
	}

	task, err := search(ctx, path, &spec)
	if err != nil {
		return nil, err
	}

	info, err := task.WaitForResult(ctx, nil)
	if err != nil {
		return nil, err
	}

	switch r := info.Result.(type) {
	case types.HostDatastoreBrowserSearchResults:
		return []types.HostDatastoreBrowserSearchResults{r}, nil
	case types.ArrayOfHostDatastoreBrowserSearchResults:
		return r.HostDatastoreBrowserSearchResults, nil
	default:
		panic(fmt.Sprintf("unknown result type: %T", r))
	}
}
Beispiel #19
0
func TestHandlerPostListWithReferenceNoRouter(t *testing.T) {
	s := mem.NewHandler()
	index := resource.NewIndex()
	index.Bind("foo", schema.Schema{Fields: schema.Fields{"id": {}}}, s, resource.DefaultConf)
	bar := index.Bind("bar", schema.Schema{Fields: schema.Fields{
		"id":  {},
		"foo": {Validator: &schema.Reference{Path: "foo"}},
	}}, s, resource.DefaultConf)
	r, _ := http.NewRequest("POST", "/bar", bytes.NewBufferString(`{"id": "1", "foo": "nonexisting"}`))
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "bar",
				Resource: bar,
			},
		},
	}
	status, _, body := listPost(context.TODO(), r, rm)
	assert.Equal(t, http.StatusInternalServerError, status)
	if assert.IsType(t, &Error{}, body) {
		err := body.(*Error)
		assert.Equal(t, http.StatusInternalServerError, err.Code)
		assert.Equal(t, "Router not available in context", err.Message)
	}
}
Beispiel #20
0
func (cmd *ovfx) NetworkMap(e *ovf.Envelope) (p []types.OvfNetworkMapping) {
	ctx := context.TODO()
	finder, err := cmd.DatastoreFlag.Finder()
	if err != nil {
		return
	}

	networks := map[string]string{}

	if e.Network != nil {
		for _, net := range e.Network.Networks {
			networks[net.Name] = net.Name
		}
	}

	for _, net := range cmd.Options.NetworkMapping {
		networks[net.Name] = net.Network
	}

	for src, dst := range networks {
		if net, err := finder.Network(ctx, dst); err == nil {
			p = append(p, types.OvfNetworkMapping{
				Name:    src,
				Network: net.Reference(),
			})
		}
	}
	return
}
func (client *localClient) Unmount(logger lager.Logger, driverId string, volumeName string) error {
	logger = logger.Session("unmount")
	logger.Info("start")
	defer logger.Info("end")
	logger.Debug("unmounting-volume", lager.Data{"volumeName": volumeName})

	unmountStart := client.clock.Now()

	defer func() {
		sendUnmountDurationMetrics(logger, time.Since(unmountStart), driverId)
	}()

	driver, found := client.driverRegistry.Driver(driverId)
	if !found {
		err := errors.New("Driver '" + driverId + "' not found in list of known drivers")
		logger.Error("mount-driver-lookup-error", err)
		volmanUnmountErrorsCounter.Increment()
		return err
	}

	env := driverhttp.NewHttpDriverEnv(logger, context.TODO())

	if response := driver.Unmount(env, voldriver.UnmountRequest{Name: volumeName}); response.Err != "" {
		err := errors.New(response.Err)
		logger.Error("unmount-failed", err)
		volmanUnmountErrorsCounter.Increment()
		return err
	}

	return nil
}
Beispiel #22
0
func (f *AutostartFlag) ReconfigureDefaults(template types.AutoStartDefaults) error {
	ctx := context.TODO()
	c, err := f.Client()
	if err != nil {
		return err
	}

	mhas, err := f.HostAutoStartManager()
	if err != nil {
		return err
	}

	req := types.ReconfigureAutostart{
		This: mhas.Reference(),
		Spec: types.HostAutoStartManagerConfig{
			Defaults: &template,
		},
	}

	_, err = methods.ReconfigureAutostart(ctx, c, &req)
	if err != nil {
		return err
	}

	return nil
}
Beispiel #23
0
func (flag *HostSystemFlag) HostSystemIfSpecified() (*object.HostSystem, error) {
	if flag.host != nil {
		return flag.host, nil
	}

	// Use search flags if specified.
	if flag.SearchFlag.IsSet() {
		host, err := flag.SearchFlag.HostSystem()
		if err != nil {
			return nil, err
		}

		flag.host = host
		return flag.host, nil
	}

	// Never look for a default host system.
	// A host system parameter is optional for vm creation. It uses a mandatory
	// resource pool parameter to determine where the vm should be placed.
	if flag.name == "" {
		return nil, nil
	}

	finder, err := flag.Finder()
	if err != nil {
		return nil, err
	}

	flag.host, err = finder.HostSystem(context.TODO(), flag.name)
	return flag.host, err
}
Beispiel #24
0
func TestHandlerPatchItemInvalidLookupFields(t *testing.T) {
	index := resource.NewIndex()
	test := index.Bind("test", schema.Schema{}, nil, resource.DefaultConf)
	r, _ := http.NewRequest("PATCH", "/test/2", bytes.NewBufferString("{}"))
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "test",
				Field:    "id",
				Value:    "2",
				Resource: test,
			},
		},
		Params: url.Values{
			"fields": []string{"invalid"},
		},
	}
	status, headers, body := itemPatch(context.TODO(), r, rm)
	assert.Equal(t, 422, status)
	assert.Nil(t, headers)
	if assert.IsType(t, body, &Error{}) {
		err := body.(*Error)
		assert.Equal(t, 422, err.Code)
		assert.Equal(t, "Invalid `fields` paramter: invalid: unknown field", err.Message)
	}
}
Beispiel #25
0
func TestHandlerPatchItemNoStorage(t *testing.T) {
	index := resource.NewIndex()
	test := index.Bind("test", schema.Schema{Fields: schema.Fields{"id": {}}}, nil, resource.Conf{
		AllowedModes: []resource.Mode{resource.Replace},
	})
	r, _ := http.NewRequest("PATCH", "/test/1", bytes.NewBufferString(`{}`))
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "test",
				Field:    "id",
				Value:    "1",
				Resource: test,
			},
		},
	}
	status, headers, body := itemPatch(context.TODO(), r, rm)
	assert.Equal(t, http.StatusNotImplemented, status)
	assert.Nil(t, headers)
	if assert.IsType(t, body, &Error{}) {
		err := body.(*Error)
		assert.Equal(t, http.StatusNotImplemented, err.Code)
		assert.Equal(t, "No Storage Defined", err.Message)
	}
}
Beispiel #26
0
func (cmd *vmdk) DetachDisk(vm *object.VirtualMachine) (string, error) {
	ctx := context.TODO()
	var mvm mo.VirtualMachine

	pc := property.DefaultCollector(cmd.Client)
	err := pc.RetrieveOne(ctx, vm.Reference(), []string{"config.hardware"}, &mvm)
	if err != nil {
		return "", err
	}

	spec := new(configSpec)
	dsFile := spec.RemoveDisk(&mvm)

	task, err := vm.Reconfigure(ctx, spec.ToSpec())
	if err != nil {
		return "", err
	}

	err = task.Wait(ctx)
	if err != nil {
		return "", err
	}

	return dsFile, nil
}
Beispiel #27
0
func contextKeyTypeTests() {
	fmt.Println()                               // not in package context
	context.TODO()                              // wrong function
	c := context.Background()                   // wrong function
	context.WithValue(c, "foo", "bar")          // MATCH /should not use basic type( untyped|)? string as key in context.WithValue/
	context.WithValue(c, true, "bar")           // MATCH /should not use basic type( untyped|)? bool as key in context.WithValue/
	context.WithValue(c, 1, "bar")              // MATCH /should not use basic type( untyped|)? int as key in context.WithValue/
	context.WithValue(c, int8(1), "bar")        // MATCH /should not use basic type int8 as key in context.WithValue/
	context.WithValue(c, int16(1), "bar")       // MATCH /should not use basic type int16 as key in context.WithValue/
	context.WithValue(c, int32(1), "bar")       // MATCH /should not use basic type int32 as key in context.WithValue/
	context.WithValue(c, rune(1), "bar")        // MATCH /should not use basic type rune as key in context.WithValue/
	context.WithValue(c, int64(1), "bar")       // MATCH /should not use basic type int64 as key in context.WithValue/
	context.WithValue(c, uint(1), "bar")        // MATCH /should not use basic type uint as key in context.WithValue/
	context.WithValue(c, uint8(1), "bar")       // MATCH /should not use basic type uint8 as key in context.WithValue/
	context.WithValue(c, byte(1), "bar")        // MATCH /should not use basic type byte as key in context.WithValue/
	context.WithValue(c, uint16(1), "bar")      // MATCH /should not use basic type uint16 as key in context.WithValue/
	context.WithValue(c, uint32(1), "bar")      // MATCH /should not use basic type uint32 as key in context.WithValue/
	context.WithValue(c, uint64(1), "bar")      // MATCH /should not use basic type uint64 as key in context.WithValue/
	context.WithValue(c, uintptr(1), "bar")     // MATCH /should not use basic type uintptr as key in context.WithValue/
	context.WithValue(c, float32(1.0), "bar")   // MATCH /should not use basic type float32 as key in context.WithValue/
	context.WithValue(c, float64(1.0), "bar")   // MATCH /should not use basic type float64 as key in context.WithValue/
	context.WithValue(c, complex64(1i), "bar")  // MATCH /should not use basic type complex64 as key in context.WithValue/
	context.WithValue(c, complex128(1i), "bar") // MATCH /should not use basic type complex128 as key in context.WithValue/
	context.WithValue(c, ctxKey{}, "bar")       // ok
	context.WithValue(c, &ctxKey{}, "bar")      // ok
}
Beispiel #28
0
// pipeStream relays over a stream to a remote peer. It's like `cat`
func (rs *RelayService) pipeStream(src, dst peer.ID, s inet.Stream) error {
	// TODO: find a good way to pass contexts into here
	nsctx, cancel := context.WithTimeout(context.TODO(), time.Second*30)
	defer cancel()

	s2, err := rs.openStreamToPeer(nsctx, dst)
	if err != nil {
		return fmt.Errorf("failed to open stream to peer: %s -- %s", dst, err)
	}
	cancel() // cancel here because this function might last a while

	if err := WriteHeader(s2, src, dst); err != nil {
		return err
	}

	// connect the series of tubes.
	done := make(chan retio, 2)
	go func() {
		n, err := io.Copy(s2, s)
		done <- retio{n, err}
	}()
	go func() {
		n, err := io.Copy(s, s2)
		done <- retio{n, err}
	}()

	r1 := <-done
	r2 := <-done
	log.Infof("%s relayed %d/%d bytes between %s and %s", rs.host.ID(), r1.n, r2.n, src, dst)

	if r1.err != nil {
		return r1.err
	}
	return r2.err
}
func TestFetchGraph(t *testing.T) {
	var dservs []DAGService
	bsis := bstest.Mocks(2)
	for _, bsi := range bsis {
		dservs = append(dservs, NewDAGService(bsi))
	}

	read := io.LimitReader(u.NewTimeSeededRand(), 1024*32)
	root, err := imp.BuildDagFromReader(dservs[0], chunk.NewSizeSplitter(read, 512))
	if err != nil {
		t.Fatal(err)
	}

	err = FetchGraph(context.TODO(), root.Cid(), dservs[1])
	if err != nil {
		t.Fatal(err)
	}

	// create an offline dagstore and ensure all blocks were fetched
	bs := bserv.New(bsis[1].Blockstore(), offline.Exchange(bsis[1].Blockstore()))

	offline_ds := NewDAGService(bs)

	err = EnumerateChildren(context.Background(), offline_ds, root.Cid(), func(_ *cid.Cid) bool { return true }, false)
	if err != nil {
		t.Fatal(err)
	}
}
Beispiel #30
0
func (flag *VirtualMachineFlag) VirtualMachine() (*object.VirtualMachine, error) {
	ctx := context.TODO()

	if flag.vm != nil {
		return flag.vm, nil
	}

	// Use search flags if specified.
	if flag.SearchFlag.IsSet() {
		vm, err := flag.SearchFlag.VirtualMachine()
		if err != nil {
			return nil, err
		}

		flag.vm = vm
		return flag.vm, nil
	}

	// Never look for a default virtual machine.
	if flag.name == "" {
		return nil, nil
	}

	finder, err := flag.Finder()
	if err != nil {
		return nil, err
	}

	flag.vm, err = finder.VirtualMachine(ctx, flag.name)
	return flag.vm, err
}