github.com/fafucoder/cilium@v1.6.11/cilium/cmd/endpoint_labels.go (about) 1 // Copyright 2017 Authors of Cilium 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 cmd 16 17 import ( 18 "fmt" 19 "os" 20 "text/tabwriter" 21 22 "github.com/cilium/cilium/pkg/color" 23 endpointid "github.com/cilium/cilium/pkg/endpoint/id" 24 "github.com/cilium/cilium/pkg/labels" 25 "github.com/cilium/cilium/pkg/labels/model" 26 "github.com/cilium/cilium/pkg/logging/logfields" 27 28 "github.com/spf13/cobra" 29 ) 30 31 var ( 32 toAdd []string 33 toDelete []string 34 ) 35 36 // endpointLabelsCmd represents the endpoint_labels command 37 var endpointLabelsCmd = &cobra.Command{ 38 Use: "labels", 39 Short: "Manage label configuration of endpoint", 40 PreRun: requireEndpointID, 41 Run: func(cmd *cobra.Command, args []string) { 42 _, id, _ := endpointid.Parse(args[0]) 43 addLabels := labels.NewLabelsFromModel(toAdd).GetModel() 44 45 deleteLabels := labels.NewLabelsFromModel(toDelete).GetModel() 46 47 if len(addLabels) > 0 || len(deleteLabels) > 0 { 48 if err := client.EndpointLabelsPatch(id, addLabels, deleteLabels); err != nil { 49 Fatalf("Cannot modifying labels %s", err) 50 } 51 } 52 53 lbls, err := client.EndpointLabelsGet(id) 54 switch { 55 case err != nil: 56 Fatalf("Cannot get endpoint labels: %s", err) 57 case lbls == nil || lbls.Status == nil: 58 Fatalf("Cannot get endpoint labels: empty response") 59 default: 60 printEndpointLabels(model.NewOplabelsFromModel(lbls.Status)) 61 } 62 }, 63 } 64 65 func init() { 66 endpointCmd.AddCommand(endpointLabelsCmd) 67 endpointLabelsCmd.Flags().StringSliceVarP(&toAdd, "add", "a", []string{}, "Add/enable labels") 68 endpointLabelsCmd.Flags().StringSliceVarP(&toDelete, "delete", "d", []string{}, "Delete/disable labels") 69 } 70 71 // printEndpointLabels pretty prints labels with tabs 72 func printEndpointLabels(lbls *labels.OpLabels) { 73 log.WithField(logfields.Labels, logfields.Repr(*lbls)).Debug("All Labels") 74 w := tabwriter.NewWriter(os.Stdout, 2, 0, 3, ' ', 0) 75 76 for _, v := range lbls.IdentityLabels() { 77 text := color.Green("Enabled") 78 fmt.Fprintf(w, "%s\t%s\n", v, text) 79 } 80 81 for _, v := range lbls.Disabled { 82 text := color.Red("Disabled") 83 fmt.Fprintf(w, "%s\t%s\n", v, text) 84 } 85 w.Flush() 86 }