github.com/fafucoder/cilium@v1.6.11/cilium/cmd/service_get.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  	"strconv"
    21  
    22  	"github.com/cilium/cilium/pkg/command"
    23  	"github.com/cilium/cilium/pkg/loadbalancer"
    24  
    25  	"github.com/spf13/cobra"
    26  )
    27  
    28  // serviceGetCmd represents the service_get command
    29  var serviceGetCmd = &cobra.Command{
    30  	Use:    "get <service id>",
    31  	Short:  "Display service information",
    32  	PreRun: requireServiceID,
    33  	Run: func(cmd *cobra.Command, args []string) {
    34  		svcIDstr := args[0]
    35  		id, err := strconv.ParseInt(svcIDstr, 0, 64)
    36  		if err != nil {
    37  			Fatalf("Unable to parse service ID: %s", svcIDstr)
    38  		}
    39  
    40  		svc, err := client.GetServiceID(id)
    41  		if err != nil {
    42  			Fatalf("Cannot get service '%v': %s\n", id, err)
    43  		}
    44  		if svc.Status == nil || svc.Status.Realized == nil {
    45  			Fatalf("Cannot get service '%v': empty response\n", id)
    46  		}
    47  
    48  		slice := []string{}
    49  		for _, be := range svc.Status.Realized.BackendAddresses {
    50  			if bea, err := loadbalancer.NewL3n4AddrFromBackendModel(be); err != nil {
    51  				slice = append(slice, fmt.Sprintf("invalid backend: %+v", be))
    52  			} else {
    53  				slice = append(slice, bea.String())
    54  			}
    55  		}
    56  
    57  		if command.OutputJSON() {
    58  			if err := command.PrintOutput(svc); err != nil {
    59  				os.Exit(1)
    60  			}
    61  			return
    62  		}
    63  
    64  		if fea, err := loadbalancer.NewL3n4AddrFromModel(svc.Status.Realized.FrontendAddress); err != nil {
    65  			fmt.Fprintf(os.Stderr, "invalid frontend model: %s", err)
    66  		} else {
    67  			fmt.Printf("%s =>\n", fea.String())
    68  		}
    69  
    70  		for i, be := range slice {
    71  			fmt.Printf("\t\t%d => %s (%d)\n", i+1, be, svc.Status.Realized.ID)
    72  		}
    73  	},
    74  }
    75  
    76  func init() {
    77  	serviceCmd.AddCommand(serviceGetCmd)
    78  	command.AddJSONOutput(serviceGetCmd)
    79  }