Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add batch APIs for multiple tags to object #2211

Merged
merged 1 commit into from
Dec 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions vapi/simulator/simulator.go
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,7 @@ func (s *handler) tagID(w http.ResponseWriter, r *http.Request) {
}
}

// TODO: support cardinality checks
func (s *handler) association(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
Expand All @@ -610,6 +611,7 @@ func (s *handler) association(w http.ResponseWriter, r *http.Request) {
}
}
OK(w, ids)

case "list-attached-objects-on-tags":
var res []tags.AttachedObjects
for _, id := range spec.TagIDs {
Expand All @@ -620,6 +622,7 @@ func (s *handler) association(w http.ResponseWriter, r *http.Request) {
res = append(res, o)
}
OK(w, res)

case "list-attached-tags-on-objects":
var res []tags.AttachedTags
for _, ref := range spec.ObjectIDs {
Expand All @@ -632,6 +635,56 @@ func (s *handler) association(w http.ResponseWriter, r *http.Request) {
res = append(res, o)
}
OK(w, res)

case "attach-multiple-tags-to-object":
// TODO: add check if target (moref) exist or return 403 as per API behavior

res := struct {
Success bool `json:"success"`
Errors tags.BatchErrors `json:"error_messages,omitempty"`
}{}

for _, id := range spec.TagIDs {
if _, exists := s.Association[id]; !exists {
log.Printf("association tag not found: %s", id)
res.Errors = append(res.Errors, tags.BatchError{
Type: "cis.tagging.objectNotFound.error",
Message: fmt.Sprintf("Tagging object %s not found", id),
})
} else {
s.Association[id][*spec.ObjectID] = true
}
}

if len(res.Errors) == 0 {
res.Success = true
}
OK(w, res)

case "detach-multiple-tags-from-object":
// TODO: add check if target (moref) exist or return 403 as per API behavior

res := struct {
Success bool `json:"success"`
Errors tags.BatchErrors `json:"error_messages,omitempty"`
}{}

for _, id := range spec.TagIDs {
if _, exists := s.Association[id]; !exists {
log.Printf("association tag not found: %s", id)
res.Errors = append(res.Errors, tags.BatchError{
Type: "cis.tagging.objectNotFound.error",
Message: fmt.Sprintf("Tagging object %s not found", id),
})
} else {
s.Association[id][*spec.ObjectID] = false
}
}

if len(res.Errors) == 0 {
res.Success = true
}
OK(w, res)
}
}

Expand Down
55 changes: 55 additions & 0 deletions vapi/tags/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
Copyright (c) 2020 VMware, Inc. All Rights Reserved.

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 tags

import (
"fmt"
)

const (
errFormat = "[error: %d type: %s reason: %s]"
separator = "," // concat multiple error strings
)

// BatchError is an error returned for a single item which failed in a batch
// operation
type BatchError struct {
Type string `json:"id"`
Message string `json:"default_message"`
}

// BatchErrors contains all errors which occurred in a batch operation
type BatchErrors []BatchError

func (b BatchErrors) Error() string {
if len(b) == 0 {
return ""
}

var errString string
for i := range b {
errType := b[i].Type
reason := b[i].Message
errString += fmt.Sprintf(errFormat, i, errType, reason)

// no separator after last item
if i+1 < len(b) {
errString += separator
}
}
return errString
}
114 changes: 113 additions & 1 deletion vapi/tags/tag_association.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,19 @@ func (c *Manager) DetachTag(ctx context.Context, tagID string, ref mo.Reference)
return c.Do(ctx, url.Request(http.MethodPost, spec), nil)
}

// AttachTagToMultipleObjects attaches a tag ID to multiple managed objects
// batchResponse is the response type used by attach/detach operations which
// take multiple tagIDs or moRefs as input. On failure Success will be false and
// Errors contains information about all failed operations
type batchResponse struct {
Success bool `json:"success"`
Errors BatchErrors `json:"error_messages,omitempty"`
}

// AttachTagToMultipleObjects attaches a tag ID to multiple managed objects.
// This operation is idempotent, i.e. if a tag is already attached to the
// object, then the individual operation is a no-op and no error will be thrown.
//
// This operation was added in vSphere API 6.5.
func (c *Manager) AttachTagToMultipleObjects(ctx context.Context, tagID string, refs []mo.Reference) error {
id, err := c.tagID(ctx, tagID)
if err != nil {
Expand All @@ -80,6 +92,106 @@ func (c *Manager) AttachTagToMultipleObjects(ctx context.Context, tagID string,
return c.Do(ctx, url.Request(http.MethodPost, spec), nil)
}

// AttachMultipleTagsToObject attaches multiple tag IDs to a managed object.
// This operation is idempotent. If a tag is already attached to the object,
// then the individual operation is a no-op and no error will be thrown. This
// operation is not atomic. If the underlying call fails with one or more tags
// not successfully attached to the managed object reference it might leave the
// managed object reference in a partially tagged state and needs to be resolved
// by the caller. In this case BatchErrors is returned and can be used to
// analyse failure reasons on each failed tag.
//
// Specified tagIDs must use URN-notation instead of display names or a generic
// error will be returned and no tagging operation will be performed. If the
// managed object reference does not exist a generic 403 Forbidden error will be
// returned.
//
// This operation was added in vSphere API 6.5.
func (c *Manager) AttachMultipleTagsToObject(ctx context.Context, tagIDs []string, ref mo.Reference) error {
for _, id := range tagIDs {
// URN enforced to avoid unnecessary round-trips due to invalid tags or display
// name lookups
if isName(id) {
return fmt.Errorf("specified tag is not a URN: %q", id)
}
}

obj := internal.AssociatedObject(ref.Reference())
spec := struct {
ObjectID internal.AssociatedObject `json:"object_id"`
TagIDs []string `json:"tag_ids"`
}{
ObjectID: obj,
TagIDs: tagIDs,
}

var res batchResponse
url := c.Resource(internal.AssociationPath).WithAction("attach-multiple-tags-to-object")
err := c.Do(ctx, url.Request(http.MethodPost, spec), &res)
if err != nil {
return err
}

if !res.Success {
if len(res.Errors) != 0 {
return res.Errors
}
panic("invalid batch error")
}

return nil
}

// DetachMultipleTagsFromObject detaches multiple tag IDs from a managed object.
// This operation is idempotent. If a tag is already detached from the object,
// then the individual operation is a no-op and no error will be thrown. This
// operation is not atomic. If the underlying call fails with one or more tags
// not successfully detached from the managed object reference it might leave
// the managed object reference in a partially tagged state and needs to be
// resolved by the caller. In this case BatchErrors is returned and can be used
// to analyse failure reasons on each failed tag.
//
// Specified tagIDs must use URN-notation instead of display names or a generic
// error will be returned and no tagging operation will be performed. If the
// managed object reference does not exist a generic 403 Forbidden error will be
// returned.
//
// This operation was added in vSphere API 6.5.
func (c *Manager) DetachMultipleTagsFromObject(ctx context.Context, tagIDs []string, ref mo.Reference) error {
for _, id := range tagIDs {
// URN enforced to avoid unnecessary round-trips due to invalid tags or display
// name lookups
if isName(id) {
return fmt.Errorf("specified tag is not a URN: %q", id)
}
}

obj := internal.AssociatedObject(ref.Reference())
spec := struct {
ObjectID internal.AssociatedObject `json:"object_id"`
TagIDs []string `json:"tag_ids"`
}{
ObjectID: obj,
TagIDs: tagIDs,
}

var res batchResponse
url := c.Resource(internal.AssociationPath).WithAction("detach-multiple-tags-from-object")
err := c.Do(ctx, url.Request(http.MethodPost, spec), &res)
if err != nil {
return err
}

if !res.Success {
if len(res.Errors) != 0 {
return res.Errors
}
panic("invalid batch error")
}

return nil
}

// ListAttachedTags fetches the array of tag IDs attached to the given object.
func (c *Manager) ListAttachedTags(ctx context.Context, ref mo.Reference) ([]string, error) {
spec := internal.NewAssociation(ref)
Expand Down
Loading