github.com/jmrodri/operator-sdk@v0.5.0/pkg/scaffold/cmd.go (about)

     1  // Copyright 2018 The Operator-SDK Authors
     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 scaffold
    16  
    17  import (
    18  	"path/filepath"
    19  
    20  	"github.com/operator-framework/operator-sdk/pkg/scaffold/input"
    21  )
    22  
    23  const CmdFile = "main.go"
    24  
    25  type Cmd struct {
    26  	input.Input
    27  }
    28  
    29  func (s *Cmd) GetInput() (input.Input, error) {
    30  	if s.Path == "" {
    31  		s.Path = filepath.Join(ManagerDir, CmdFile)
    32  	}
    33  	s.TemplateBody = cmdTmpl
    34  	return s.Input, nil
    35  }
    36  
    37  const cmdTmpl = `package main
    38  
    39  import (
    40  	"context"
    41  	"flag"
    42  	"fmt"
    43  	"os"
    44  	"runtime"
    45  
    46  	"{{ .Repo }}/pkg/apis"
    47  	"{{ .Repo }}/pkg/controller"
    48  
    49  	"github.com/operator-framework/operator-sdk/pkg/k8sutil"
    50  	"github.com/operator-framework/operator-sdk/pkg/leader"
    51  	"github.com/operator-framework/operator-sdk/pkg/log/zap"
    52  	"github.com/operator-framework/operator-sdk/pkg/metrics"
    53  	sdkVersion "github.com/operator-framework/operator-sdk/version"
    54  	"github.com/spf13/pflag"
    55  	_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
    56  	"sigs.k8s.io/controller-runtime/pkg/client/config"
    57  	"sigs.k8s.io/controller-runtime/pkg/manager"
    58  	logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
    59  	"sigs.k8s.io/controller-runtime/pkg/runtime/signals"
    60  )
    61  
    62  // Change below variables to serve metrics on different host or port.
    63  var (
    64      metricsHost = "0.0.0.0"
    65      metricsPort int32 = 8383
    66  )
    67  var log = logf.Log.WithName("cmd")
    68  
    69  func printVersion() {
    70  	log.Info(fmt.Sprintf("Go Version: %s", runtime.Version()))
    71  	log.Info(fmt.Sprintf("Go OS/Arch: %s/%s", runtime.GOOS, runtime.GOARCH))
    72  	log.Info(fmt.Sprintf("Version of operator-sdk: %v", sdkVersion.Version))
    73  }
    74  
    75  func main() {
    76  	// Add the zap logger flag set to the CLI. The flag set must
    77  	// be added before calling pflag.Parse().
    78  	pflag.CommandLine.AddFlagSet(zap.FlagSet())
    79  
    80  	// Add flags registered by imported packages (e.g. glog and
    81  	// controller-runtime)
    82  	pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
    83  
    84  	pflag.Parse()
    85  
    86  	// Use a zap logr.Logger implementation. If none of the zap
    87  	// flags are configured (or if the zap flag set is not being
    88  	// used), this defaults to a production zap logger.
    89  	//
    90  	// The logger instantiated here can be changed to any logger
    91  	// implementing the logr.Logger interface. This logger will
    92  	// be propagated through the whole operator, generating
    93  	// uniform and structured logs.
    94  	logf.SetLogger(zap.Logger())
    95  
    96  	printVersion()
    97  
    98  	namespace, err := k8sutil.GetWatchNamespace()
    99  	if err != nil {
   100  		log.Error(err, "Failed to get watch namespace")
   101  		os.Exit(1)
   102  	}
   103  
   104  	// Get a config to talk to the apiserver
   105  	cfg, err := config.GetConfig()
   106  	if err != nil {
   107  		log.Error(err, "")
   108  		os.Exit(1)
   109  	}
   110  	
   111  	ctx := context.TODO()
   112  
   113  	// Become the leader before proceeding
   114  	err = leader.Become(ctx, "{{ .ProjectName }}-lock")
   115  	if err != nil {
   116  		log.Error(err, "")
   117  		os.Exit(1)
   118  	}
   119  
   120  	// Create a new Cmd to provide shared dependencies and start components
   121  	mgr, err := manager.New(cfg, manager.Options{
   122  		Namespace:          namespace,
   123  		MetricsBindAddress: fmt.Sprintf("%s:%d", metricsHost, metricsPort),
   124  	})	
   125  	if err != nil {
   126  		log.Error(err, "")
   127  		os.Exit(1)
   128  	}
   129  
   130  	log.Info("Registering Components.")
   131  
   132  	// Setup Scheme for all resources
   133  	if err := apis.AddToScheme(mgr.GetScheme()); err != nil {
   134  		log.Error(err, "")
   135  		os.Exit(1)
   136  	}
   137  
   138  	// Setup all Controllers
   139  	if err := controller.AddToManager(mgr); err != nil {
   140  		log.Error(err, "")
   141  		os.Exit(1)
   142  	}
   143  
   144  	// Create Service object to expose the metrics port.
   145  	_, err = metrics.ExposeMetricsPort(ctx, metricsPort)
   146  	if err != nil {
   147  		log.Info(err.Error())
   148  	}
   149  
   150  	log.Info("Starting the Cmd.")
   151  
   152  	// Start the Cmd
   153  	if err := mgr.Start(signals.SetupSignalHandler()); err != nil {
   154  		log.Error(err, "Manager exited non-zero")
   155  		os.Exit(1)
   156  	}
   157  }
   158  `