github.com/fafucoder/cilium@v1.6.11/cilium/cmd/node_list.go (about) 1 // Copyright 2018-2019 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 "io" 20 "os" 21 "sort" 22 "text/tabwriter" 23 24 "github.com/cilium/cilium/api/v1/models" 25 pkg "github.com/cilium/cilium/pkg/client" 26 "github.com/cilium/cilium/pkg/command" 27 28 "github.com/spf13/cobra" 29 ) 30 31 var nodeListCmd = &cobra.Command{ 32 Use: "list", 33 Aliases: []string{"ls"}, 34 Short: "List nodes", 35 Run: func(cmd *cobra.Command, args []string) { 36 resp, err := client.Daemon.GetClusterNodes(nil) 37 if err != nil { 38 fmt.Fprintf(os.Stderr, "%s\n", pkg.Hint(err)) 39 os.Exit(1) 40 } 41 42 cluster := resp.Payload.NodesAdded 43 if cluster == nil { 44 return 45 } 46 47 if command.OutputJSON() { 48 if err := command.PrintOutput(cluster); err != nil { 49 os.Exit(1) 50 } 51 } else { 52 w := tabwriter.NewWriter(os.Stdout, 2, 0, 3, ' ', 0) 53 formatStatusResponse(w, cluster) 54 w.Flush() 55 } 56 }, 57 } 58 59 func init() { 60 nodeCmd.AddCommand(nodeListCmd) 61 command.AddJSONOutput(nodeListCmd) 62 } 63 64 func formatStatusResponse(w io.Writer, nodes []*models.NodeElement) { 65 nodesOutput := []string{"Name\tIPv4 Address\tEndpoint CIDR\tIPv6 Address\tEndpoint CIDR\n"} 66 67 for _, node := range nodes { 68 ipv4, ipv4Range, ipv6, ipv6Range := "", "", "", "" 69 if node.PrimaryAddress != nil { 70 if node.PrimaryAddress.IPV4 != nil { 71 ipv4 = node.PrimaryAddress.IPV4.IP 72 ipv4Range = node.PrimaryAddress.IPV4.AllocRange 73 } 74 if node.PrimaryAddress.IPV6 != nil { 75 ipv6 = node.PrimaryAddress.IPV6.IP 76 ipv6Range = node.PrimaryAddress.IPV6.AllocRange 77 } 78 } 79 80 nodesOutput = append(nodesOutput, fmt.Sprintf("%s\t%s\t%s\t%s\t%s\n", 81 node.Name, ipv4, ipv4Range, ipv6, ipv6Range)) 82 } 83 84 if len(nodesOutput) > 1 { 85 tab := tabwriter.NewWriter(w, 0, 0, 3, ' ', 0) 86 sort.Strings(nodesOutput) 87 for _, s := range nodesOutput { 88 fmt.Fprint(tab, s) 89 } 90 tab.Flush() 91 } 92 }