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