github.com/olli-ai/jx/v2@v2.0.400-0.20210921045218-14731b4dd448/pkg/cmd/get/get_env.go (about)

     1  package get
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/olli-ai/jx/v2/pkg/cmd/helper"
     8  
     9  	v1 "github.com/jenkins-x/jx-api/pkg/apis/jenkins.io/v1"
    10  	"github.com/jenkins-x/jx-logging/pkg/log"
    11  	"github.com/olli-ai/jx/v2/pkg/cmd/opts"
    12  	"github.com/olli-ai/jx/v2/pkg/cmd/templates"
    13  	"github.com/olli-ai/jx/v2/pkg/kube"
    14  	"github.com/olli-ai/jx/v2/pkg/util"
    15  	"github.com/spf13/cobra"
    16  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    17  )
    18  
    19  // GetEnvOptions containers the CLI options
    20  type GetEnvOptions struct {
    21  	Options
    22  
    23  	PromotionStrategy string
    24  	PreviewOnly       bool
    25  }
    26  
    27  var (
    28  	getEnvLong = templates.LongDesc(`
    29  		Display one or more environments.
    30  ` + helper.SeeAlsoText("jx get previews"))
    31  
    32  	getEnvExample = templates.Examples(`
    33  		# List all environments
    34  		jx get environments
    35  
    36  		# List all environments using the shorter alias
    37  		jx get env
    38  	`)
    39  )
    40  
    41  // NewCmdGetEnv creates the new command for: jx get env
    42  func NewCmdGetEnv(commonOpts *opts.CommonOptions) *cobra.Command {
    43  	options := &GetEnvOptions{
    44  		Options: Options{
    45  			CommonOptions: commonOpts,
    46  		},
    47  	}
    48  	cmd := &cobra.Command{
    49  		Use:     "environments",
    50  		Short:   "Display one or more Environments",
    51  		Aliases: []string{"envs", "environment", "env"},
    52  		Long:    getEnvLong,
    53  		Example: getEnvExample,
    54  		Run: func(cmd *cobra.Command, args []string) {
    55  			options.Cmd = cmd
    56  			options.Args = args
    57  			err := options.Run()
    58  			helper.CheckErr(err)
    59  		},
    60  	}
    61  
    62  	options.AddGetFlags(cmd)
    63  
    64  	cmd.Flags().StringVarP(&options.PromotionStrategy, "promote", "p", "", "Filters the environments by promotion strategy. Possible values: "+strings.Join(v1.PromotionStrategyTypeValues, ", "))
    65  	_ = cmd.Flags().SetAnnotation("promote", cobra.BashCompCustom, []string{"__jx_get_promotionstrategies"})
    66  
    67  	return cmd
    68  }
    69  
    70  // Run implements this command
    71  func (o *GetEnvOptions) Run() error {
    72  	client, ns, err := o.JXClientAndDevNamespace()
    73  	if err != nil {
    74  		return err
    75  	}
    76  	kubeClient, err := o.KubeClient()
    77  	if err != nil {
    78  		return err
    79  	}
    80  
    81  	args := o.Args
    82  	if len(args) > 0 {
    83  		e := args[0]
    84  		env, err := client.JenkinsV1().Environments(ns).Get(e, metav1.GetOptions{})
    85  		if err != nil {
    86  			envNames, err := kube.GetEnvironmentNames(client, ns)
    87  			if err != nil {
    88  				return err
    89  			}
    90  			return util.InvalidArg(e, envNames)
    91  		}
    92  
    93  		// lets output one environment
    94  		spec := &env.Spec
    95  
    96  		table := o.CreateTable()
    97  		table.AddRow("NAME", "LABEL", "KIND", "NAMESPACE", "SOURCE", "REF", "PR")
    98  		table.AddRow(e, spec.Label, spec.Namespace, kindString(spec), spec.Source.URL, spec.Source.Ref, spec.PullRequestURL)
    99  		table.Render()
   100  		log.Logger().Info("")
   101  
   102  		ens := env.Spec.Namespace
   103  		if ens != "" {
   104  			deps, err := kubeClient.AppsV1().Deployments(ens).List(metav1.ListOptions{})
   105  			if err != nil {
   106  				return fmt.Errorf("Could not find deployments in namespace %s: %s", ens, err)
   107  			}
   108  			table = o.CreateTable()
   109  			table.AddRow("APP", "VERSION", "DESIRED", "CURRENT", "UP-TO-DATE", "AVAILABLE", "AGE")
   110  			for _, d := range deps.Items {
   111  				replicas := ""
   112  				if d.Spec.Replicas != nil {
   113  					replicas = formatInt32(*d.Spec.Replicas)
   114  				}
   115  				table.AddRow(d.Name, kube.GetVersion(&d.ObjectMeta), replicas,
   116  					formatInt32(d.Status.ReadyReplicas), formatInt32(d.Status.UpdatedReplicas), formatInt32(d.Status.AvailableReplicas), "")
   117  			}
   118  			table.Render()
   119  		}
   120  	} else {
   121  		envs, err := client.JenkinsV1().Environments(ns).List(metav1.ListOptions{})
   122  		if err != nil {
   123  			return err
   124  		}
   125  		if len(envs.Items) == 0 {
   126  			log.Logger().Infof("No environments found.\nTo create an environment use: jx create env")
   127  			return nil
   128  		}
   129  
   130  		environments := o.filterEnvironments(envs.Items)
   131  		kube.SortEnvironments(environments)
   132  
   133  		if o.Output != "" {
   134  			envs.Items = environments
   135  			return o.renderResult(envs, o.Output)
   136  		}
   137  		table := o.CreateTable()
   138  		if o.PreviewOnly {
   139  			table.AddRow("PULL REQUEST", "NAMESPACE", "APPLICATION")
   140  		} else {
   141  			table.AddRow("NAME", "LABEL", "KIND", "PROMOTE", "NAMESPACE", "ORDER", "CLUSTER", "SOURCE", "REF", "PR")
   142  		}
   143  
   144  		for _, env := range environments {
   145  			spec := &env.Spec
   146  			if o.PreviewOnly {
   147  				table.AddRow(spec.PullRequestURL, spec.Namespace, util.ColorInfo(spec.PreviewGitSpec.ApplicationURL))
   148  			} else {
   149  				table.AddRow(env.Name, spec.Label, kindString(spec), string(spec.PromotionStrategy), spec.Namespace, util.Int32ToA(spec.Order), spec.Cluster, spec.Source.URL, spec.Source.Ref, spec.PullRequestURL)
   150  			}
   151  		}
   152  		table.Render()
   153  	}
   154  	return nil
   155  }
   156  
   157  func kindString(spec *v1.EnvironmentSpec) string {
   158  	answer := string(spec.Kind)
   159  	if answer == "" {
   160  		return string(v1.EnvironmentKindTypePermanent)
   161  	}
   162  	return answer
   163  }
   164  
   165  func (o *GetEnvOptions) filterEnvironments(envs []v1.Environment) []v1.Environment {
   166  	answer := []v1.Environment{}
   167  	for _, e := range envs {
   168  		env := e
   169  		preview := env.Spec.Kind == v1.EnvironmentKindTypePreview
   170  		if o.matchesFilter(&env) && preview == o.PreviewOnly {
   171  			answer = append(answer, env)
   172  		}
   173  	}
   174  	return answer
   175  }
   176  
   177  func (o *GetEnvOptions) matchesFilter(env *v1.Environment) bool {
   178  	if o.PromotionStrategy == "" {
   179  		return true
   180  	}
   181  	return env.Spec.PromotionStrategy == v1.PromotionStrategyType(o.PromotionStrategy)
   182  }