yunion.io/x/cloudmux@v0.3.10-0-alpha.1/pkg/cloudprovider/resourcetags.go (about)

     1  // Copyright 2019 Yunion
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package cloudprovider
    16  
    17  import (
    18  	"context"
    19  	"reflect"
    20  	"strings"
    21  	"time"
    22  
    23  	"yunion.io/x/log"
    24  	"yunion.io/x/pkg/errors"
    25  )
    26  
    27  const (
    28  	SET_TAGS = "set-tags"
    29  )
    30  
    31  type TagsUpdateInfo struct {
    32  	OldTags map[string]string
    33  	NewTags map[string]string
    34  }
    35  
    36  func (t TagsUpdateInfo) IsChanged() bool {
    37  	return !reflect.DeepEqual(t.OldTags, t.NewTags)
    38  }
    39  
    40  func SetTags(ctx context.Context, res ICloudResource, managerId string, tags map[string]string, replace bool) error {
    41  	err := res.SetTags(tags, replace)
    42  	if err != nil {
    43  		return errors.Wrapf(err, "SetTags")
    44  	}
    45  
    46  	// 避免设置标签后未及时生效,导致本地同步和云上不一致
    47  	Wait(time.Second*5, time.Minute, func() (bool, error) {
    48  		res.Refresh()
    49  		newTags, err := res.GetTags()
    50  		if err != nil {
    51  			return false, errors.Wrapf(err, "GetTags")
    52  		}
    53  		for k, v := range tags {
    54  			_, ok := newTags[k]
    55  			_, ok2 := newTags[strings.ToLower(k)]
    56  			if !ok && !ok2 {
    57  				log.Warningf("tag %s:%s not found waitting....", k, v)
    58  				return false, nil
    59  			}
    60  		}
    61  		return true, nil
    62  	})
    63  	return nil
    64  }