github.com/jenkins-x/jx/v2@v2.1.155/pkg/cmd/gc/gc_previews.go (about)

     1  package gc
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/jenkins-x/jx/v2/pkg/cmd/deletecmd"
     7  	"github.com/jenkins-x/jx/v2/pkg/cmd/preview"
     8  
     9  	"github.com/jenkins-x/jx/v2/pkg/cmd/helper"
    10  	"github.com/jenkins-x/jx/v2/pkg/cmd/promote"
    11  
    12  	"github.com/spf13/cobra"
    13  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    14  
    15  	"strconv"
    16  
    17  	"strings"
    18  
    19  	v1 "github.com/jenkins-x/jx-api/pkg/apis/jenkins.io/v1"
    20  	"github.com/jenkins-x/jx-logging/pkg/log"
    21  	"github.com/jenkins-x/jx/v2/pkg/cmd/opts"
    22  	"github.com/jenkins-x/jx/v2/pkg/cmd/templates"
    23  	"github.com/jenkins-x/jx/v2/pkg/gits"
    24  )
    25  
    26  // GetOptions is the start of the data required to perform the operation.  As new fields are added, add them here instead of
    27  // referencing the cmd.Flags()
    28  type GCPreviewsOptions struct {
    29  	*opts.CommonOptions
    30  
    31  	DisableImport bool
    32  	OutDir        string
    33  }
    34  
    35  var (
    36  	GCPreviewsLong = templates.LongDesc(`
    37  		Garbage collect Jenkins X preview environments.  If a pull request is merged or closed the associated preview
    38  		environment will be deleted.
    39  
    40  `)
    41  
    42  	GCPreviewsExample = templates.Examples(`
    43  		jx garbage collect previews
    44  		jx gc previews
    45  `)
    46  )
    47  
    48  // NewCmd s a command object for the "step" command
    49  func NewCmdGCPreviews(commonOpts *opts.CommonOptions) *cobra.Command {
    50  	options := &GCPreviewsOptions{
    51  		CommonOptions: commonOpts,
    52  	}
    53  
    54  	cmd := &cobra.Command{
    55  		Use:     "previews",
    56  		Short:   "garbage collection for preview environments",
    57  		Long:    GCPreviewsLong,
    58  		Example: GCPreviewsExample,
    59  		Run: func(cmd *cobra.Command, args []string) {
    60  			options.Cmd = cmd
    61  			options.Args = args
    62  			err := options.Run()
    63  			helper.CheckErr(err)
    64  		},
    65  	}
    66  	return cmd
    67  }
    68  
    69  // Run implements this command
    70  func (o *GCPreviewsOptions) Run() error {
    71  	client, currentNs, err := o.JXClientAndDevNamespace()
    72  	if err != nil {
    73  		return err
    74  	}
    75  
    76  	// cannot use field selectors like `spec.kind=Preview` on CRDs so list all environments
    77  	envs, err := client.JenkinsV1().Environments(currentNs).List(metav1.ListOptions{})
    78  	if err != nil {
    79  		return err
    80  	}
    81  	if len(envs.Items) == 0 {
    82  		// no environments found so lets return gracefully
    83  		log.Logger().Debug("no environments found")
    84  		return nil
    85  	}
    86  
    87  	var previewFound bool
    88  	for _, e := range envs.Items {
    89  		if e.Spec.Kind == v1.EnvironmentKindTypePreview {
    90  			previewFound = true
    91  			gitInfo, err := gits.ParseGitURL(e.Spec.Source.URL)
    92  			if err != nil {
    93  				return err
    94  			}
    95  			// we need pull request info to include
    96  			authConfigSvc, err := o.GitAuthConfigService()
    97  			if err != nil {
    98  				return err
    99  			}
   100  
   101  			gitKind, err := o.GitServerKind(gitInfo)
   102  			if err != nil {
   103  				return err
   104  			}
   105  
   106  			ghOwner, err := o.GetGitHubAppOwner(gitInfo)
   107  			if err != nil {
   108  				return err
   109  			}
   110  			gitProvider, err := gitInfo.CreateProvider(o.InCluster(), authConfigSvc, gitKind, ghOwner, o.Git(), o.BatchMode, o.GetIOFileHandles())
   111  			if err != nil {
   112  				return err
   113  			}
   114  			prNum, err := strconv.Atoi(e.Spec.PreviewGitSpec.Name)
   115  			if err != nil {
   116  				log.Logger().Warn("Unable to convert PR " + e.Spec.PreviewGitSpec.Name + " to a number")
   117  			}
   118  			pullRequest, err := gitProvider.GetPullRequest(gitInfo.Organisation, gitInfo, prNum)
   119  			if err != nil {
   120  				log.Logger().Warnf("Can not get pull request %s, skipping: %s", e.Spec.PreviewGitSpec.Name, err)
   121  				continue
   122  			}
   123  
   124  			lowerState := strings.ToLower(*pullRequest.State)
   125  
   126  			if strings.HasPrefix(lowerState, "clos") || strings.HasPrefix(lowerState, "merged") || strings.HasPrefix(lowerState, "superseded") || strings.HasPrefix(lowerState, "declined") {
   127  				// lets delete the preview environment
   128  				deleteOpts := deletecmd.DeletePreviewOptions{
   129  					PreviewOptions: preview.PreviewOptions{
   130  						PromoteOptions: promote.PromoteOptions{
   131  							CommonOptions: o.CommonOptions,
   132  						},
   133  					},
   134  				}
   135  				err = deleteOpts.DeletePreview(e.Name)
   136  				if err != nil {
   137  					return fmt.Errorf("failed to delete preview environment %s: %v\n", e.Name, err)
   138  				}
   139  			}
   140  		}
   141  	}
   142  	if !previewFound {
   143  		log.Logger().Debug("no preview environments found")
   144  	}
   145  	return nil
   146  }