...

Source file src/github.com/sigstore/rekor/cmd/rekor-server/app/root.go

Documentation: github.com/sigstore/rekor/cmd/rekor-server/app

     1  //
     2  // Copyright 2021 The Sigstore Authors.
     3  //
     4  // Licensed under the Apache License, Version 2.0 (the "License");
     5  // you may not use this file except in compliance with the License.
     6  // You may obtain a copy of the License at
     7  //
     8  //     http://www.apache.org/licenses/LICENSE-2.0
     9  //
    10  // Unless required by applicable law or agreed to in writing, software
    11  // distributed under the License is distributed on an "AS IS" BASIS,
    12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  // See the License for the specific language governing permissions and
    14  // limitations under the License.
    15  
    16  package app
    17  
    18  import (
    19  	"fmt"
    20  	"net/http"
    21  	"net/http/pprof"
    22  	"os"
    23  	"time"
    24  
    25  	"github.com/go-chi/chi/middleware"
    26  	homedir "github.com/mitchellh/go-homedir"
    27  	"github.com/sigstore/rekor/pkg/log"
    28  	"github.com/spf13/cobra"
    29  	"github.com/spf13/viper"
    30  
    31  	"sigs.k8s.io/release-utils/version"
    32  )
    33  
    34  var (
    35  	cfgFile     string
    36  	logType     string
    37  	enablePprof bool
    38  	// these map to the operationId as defined in openapi.yaml file
    39  	operationIDs = []string{
    40  		"searchIndex",
    41  		"getLogInfo",
    42  		"getPublicKey",
    43  		"getLogProof",
    44  		"createLogEntry",
    45  		"getLogEntryByIndex",
    46  		"getLogEntryByUUID",
    47  		"searchLogQuery",
    48  	}
    49  )
    50  
    51  // rootCmd represents the base command when called without any subcommands
    52  var rootCmd = &cobra.Command{
    53  	Use:   "rekor-server",
    54  	Short: "Rekor signature transparency log server",
    55  	Long: `Rekor fulfills the signature transparency role of sigstore's software
    56  	signing infrastructure. It can also be run on its own and is designed to be
    57  	extensible to work with different manifest schemas and PKI tooling`,
    58  	// Uncomment the following line if your bare application
    59  	// has an action associated with it:
    60  	//	Run: func(cmd *cobra.Command, args []string) { },
    61  }
    62  
    63  // Execute adds all child commands to the root command and sets flags appropriately.
    64  // This is called by main.main(). It only needs to happen once to the rootCmd.
    65  func Execute() {
    66  	if err := rootCmd.Execute(); err != nil {
    67  		log.Logger.Error(err)
    68  		os.Exit(1)
    69  	}
    70  }
    71  
    72  func init() {
    73  	cobra.OnInitialize(initConfig)
    74  
    75  	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.rekor-server.yaml)")
    76  	rootCmd.PersistentFlags().StringVar(&logType, "log_type", "dev", "logger type to use (dev/prod)")
    77  	rootCmd.PersistentFlags().BoolVar(&enablePprof, "enable_pprof", false, "enable pprof for profiling on port 6060")
    78  
    79  	rootCmd.PersistentFlags().Bool("gcp_cloud_profiling.enabled", false, "enable GCP Cloud Profiling")
    80  	rootCmd.PersistentFlags().String("gcp_cloud_profiling.service", "rekor-server", "a name for the service being profiled")
    81  	rootCmd.PersistentFlags().String("gcp_cloud_profiling.service_version", version.GetVersionInfo().GitVersion, "the version of the service being profiled")
    82  	rootCmd.PersistentFlags().String("gcp_cloud_profiling.project_id", "", "GCP project ID")
    83  	rootCmd.PersistentFlags().Bool("gcp_cloud_profiling.enable_oc_telemetry", false, "enable Profiler spans in Cloud Tracing & Cloud Monitoring")
    84  
    85  	rootCmd.PersistentFlags().String("trillian_log_server.address", "127.0.0.1", "Trillian log server address")
    86  	rootCmd.PersistentFlags().Uint16("trillian_log_server.port", 8090, "Trillian log server port")
    87  	rootCmd.PersistentFlags().Uint("trillian_log_server.tlog_id", 0, "Trillian tree id")
    88  	rootCmd.PersistentFlags().String("trillian_log_server.sharding_config", "", "path to config file for inactive shards, in JSON or YAML")
    89  
    90  	rootCmd.PersistentFlags().Bool("enable_stable_checkpoint", true, "publish stable checkpoints to Redis. When disabled, gossiping may not be possible if the log checkpoint updates too frequently")
    91  	rootCmd.PersistentFlags().Uint("publish_frequency", 5, "how often to publish a new checkpoint, in minutes")
    92  
    93  	hostname, err := os.Hostname()
    94  	if err != nil {
    95  		hostname = "localhost"
    96  	}
    97  	rootCmd.PersistentFlags().String("rekor_server.hostname", hostname, "public hostname of instance")
    98  	rootCmd.PersistentFlags().String("rekor_server.address", "127.0.0.1", "Address to bind to")
    99  
   100  	rootCmd.PersistentFlags().String("rekor_server.signer", "memory",
   101  		`Rekor signer to use. Valid options are: [awskms://keyname, azurekms://keyname, gcpkms://keyname, hashivault://keyname, memory, <filename containing PEM-encoded private key>].
   102  Memory and file-based signers should only be used for testing.`)
   103  	rootCmd.PersistentFlags().String("rekor_server.signer-passwd", "", "Password to decrypt signer private key")
   104  
   105  	rootCmd.PersistentFlags().String("rekor_server.new_entry_publisher", "", "URL for pub/sub queue to send messages to when new entries are added to the log. Ignored if not set. Supported providers: [gcppubsub]")
   106  	rootCmd.PersistentFlags().Bool("rekor_server.publish_events_protobuf", false, "Whether to publish events in Protobuf wire format. Applies to all enabled event types.")
   107  	rootCmd.PersistentFlags().Bool("rekor_server.publish_events_json", false, "Whether to publish events in CloudEvents JSON format. Applies to all enabled event types.")
   108  
   109  	rootCmd.PersistentFlags().Uint16("port", 3000, "Port to bind to")
   110  
   111  	rootCmd.PersistentFlags().Bool("enable_retrieve_api", true, "enables Redis-based index API endpoint")
   112  	_ = rootCmd.PersistentFlags().MarkDeprecated("enable_retrieve_api", "this flag is deprecated in favor of enabled_api_endpoints (searchIndex)")
   113  	rootCmd.PersistentFlags().String("search_index.storage_provider", "redis",
   114  		`Index Storage provider to use. Valid options are: [redis, mysql].`)
   115  	rootCmd.PersistentFlags().String("redis_server.address", "127.0.0.1", "Redis server address")
   116  	rootCmd.PersistentFlags().Uint16("redis_server.port", 6379, "Redis server port")
   117  	rootCmd.PersistentFlags().String("redis_server.password", "", "Redis server password")
   118  	rootCmd.PersistentFlags().Bool("redis_server.enable-tls", false, "Whether to enable TLS verification when connecting to Redis endpoint")
   119  	rootCmd.PersistentFlags().Bool("redis_server.insecure-skip-verify", false, "Whether to skip TLS verification when connecting to Redis endpoint, only applicable when 'redis_server.enable-tls' is set to 'true'")
   120  
   121  	rootCmd.PersistentFlags().Bool("enable_attestation_storage", false, "enables rich attestation storage")
   122  	rootCmd.PersistentFlags().String("attestation_storage_bucket", "", "url for attestation storage bucket")
   123  	rootCmd.PersistentFlags().Int("max_attestation_size", 100*1024, "max size for attestation storage, in bytes")
   124  
   125  	rootCmd.PersistentFlags().StringSlice("enabled_api_endpoints", operationIDs, "list of API endpoints to enable using operationId from openapi.yaml")
   126  
   127  	rootCmd.PersistentFlags().Uint64("max_request_body_size", 0, "maximum size for HTTP request body, in bytes; set to 0 for unlimited")
   128  	rootCmd.PersistentFlags().Uint64("max_jar_metadata_size", 1048576, "maximum permitted size for jar META-INF/ files, in bytes; set to 0 for unlimited")
   129  	rootCmd.PersistentFlags().Uint64("max_apk_metadata_size", 1048576, "maximum permitted size for apk .SIGN and .PKGINFO files, in bytes; set to 0 for unlimited")
   130  
   131  	rootCmd.PersistentFlags().String("search_index.mysql.dsn", "", "DSN for index storage using MySQL")
   132  	rootCmd.PersistentFlags().Duration("search_index.mysql.conn_max_idletime", 0*time.Second, "maximum connection idle time")
   133  	rootCmd.PersistentFlags().Duration("search_index.mysql.conn_max_lifetime", 0*time.Second, "maximum connection lifetime")
   134  	rootCmd.PersistentFlags().Int("search_index.mysql.max_open_connections", 0, "maximum open connections")
   135  	rootCmd.PersistentFlags().Int("search_index.mysql.max_idle_connections", 0, "maximum idle connections")
   136  
   137  	rootCmd.PersistentFlags().String("http-request-id-header-name", middleware.RequestIDHeader, "name of HTTP Request Header to use as request correlation ID")
   138  	rootCmd.PersistentFlags().String("trace-string-prefix", "", "if set, this will be used to prefix the 'trace' field when outputting structured logs")
   139  
   140  	if err := viper.BindPFlags(rootCmd.PersistentFlags()); err != nil {
   141  		log.Logger.Fatal(err)
   142  	}
   143  
   144  	rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
   145  
   146  	log.Logger.Debugf("pprof enabled %v", enablePprof)
   147  	// Enable pprof
   148  	if enablePprof {
   149  		go func() {
   150  			mux := http.NewServeMux()
   151  
   152  			mux.HandleFunc("/debug/pprof/", pprof.Index)
   153  			mux.HandleFunc("/debug/pprof/{action}", pprof.Index)
   154  			mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
   155  
   156  			srv := &http.Server{
   157  				Addr:         ":6060",
   158  				ReadTimeout:  10 * time.Second,
   159  				WriteTimeout: 10 * time.Second,
   160  				Handler:      mux,
   161  			}
   162  
   163  			if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
   164  				log.Logger.Fatalf("Error when starting or running http server: %v", err)
   165  			}
   166  		}()
   167  	}
   168  
   169  }
   170  
   171  // initConfig reads in config file and ENV variables if set.
   172  func initConfig() {
   173  	if cfgFile != "" {
   174  		// Use config file from the flag.
   175  		viper.SetConfigFile(cfgFile)
   176  	} else {
   177  		// Find home directory.
   178  		home, err := homedir.Dir()
   179  		if err != nil {
   180  			fmt.Println(err)
   181  			os.Exit(1)
   182  		}
   183  
   184  		viper.AddConfigPath(home)
   185  		viper.AddConfigPath(".")
   186  		viper.SetConfigName("rekor-server")
   187  		viper.SetConfigType("yaml")
   188  	}
   189  
   190  	viper.AutomaticEnv() // read in environment variables that match
   191  
   192  	// If a config file is found, read it in.
   193  	if err := viper.ReadInConfig(); err == nil {
   194  		log.Logger.Infof("Using config file: %s", viper.ConfigFileUsed())
   195  	}
   196  }
   197  

View as plain text