18947: Refactor keep-web as arvados-server command.
[arvados.git] / services / keep-web / main.go
index 27ceb48c78bfebbc40aa9d3732cbcbba6ad63155..7a23cd1fad06a551310fe9efaaa7030cf0d87d91 100644 (file)
 //
 // SPDX-License-Identifier: AGPL-3.0
 
-package main
+package keepweb
 
 import (
-       "flag"
-       "log"
+       "context"
+       "mime"
        "os"
-       "time"
 
-       "git.curoverse.com/arvados.git/sdk/go/arvados"
-       "git.curoverse.com/arvados.git/sdk/go/config"
-       "github.com/coreos/go-systemd/daemon"
+       "git.arvados.org/arvados.git/lib/service"
+       "git.arvados.org/arvados.git/sdk/go/arvados"
+       "git.arvados.org/arvados.git/sdk/go/ctxlog"
+       "git.arvados.org/arvados.git/sdk/go/keepclient"
+       "github.com/prometheus/client_golang/prometheus"
 )
 
 var (
-       defaultConfigPath = "/etc/arvados/keep-web/keep-web.yml"
+       version = "dev"
 )
 
-// Config specifies server configuration.
-type Config struct {
-       Client arvados.Client
+var Command = service.Command(arvados.ServiceNameKeepweb, newHandlerOrErrorHandler)
 
-       Listen string
-
-       AnonymousTokens    []string
-       AttachmentOnlyHost string
-       TrustAllContent    bool
-
-       Cache cache
-
-       // Hack to support old command line flag, which is a bool
-       // meaning "get actual token from environment".
-       deprecatedAllowAnonymous bool
-
-       //Authorization token to be included in all health check requests.
-       ManagementToken string
-}
-
-// DefaultConfig returns the default configuration.
-func DefaultConfig() *Config {
-       return &Config{
-               Listen: ":80",
-               Cache: cache{
-                       TTL:                  arvados.Duration(5 * time.Minute),
-                       UUIDTTL:              arvados.Duration(5 * time.Second),
-                       MaxCollectionEntries: 1000,
-                       MaxCollectionBytes:   100000000,
-                       MaxPermissionEntries: 1000,
-                       MaxUUIDEntries:       1000,
-               },
-       }
-}
-
-func init() {
-       // MakeArvadosClient returns an error if this env var isn't
-       // available as a default token (even if we explicitly set a
-       // different token before doing anything with the client). We
-       // set this dummy value during init so it doesn't clobber the
-       // one used by "run test servers".
-       if os.Getenv("ARVADOS_API_TOKEN") == "" {
-               os.Setenv("ARVADOS_API_TOKEN", "xxx")
+func newHandlerOrErrorHandler(ctx context.Context, cluster *arvados.Cluster, token string, reg *prometheus.Registry) service.Handler {
+       h, err := newHandler(ctx, cluster, token, reg)
+       if err != nil {
+               return service.ErrorHandler(ctx, cluster, err)
        }
+       return h
 }
 
-func main() {
-       cfg := DefaultConfig()
-
-       var configPath string
-       deprecated := " (DEPRECATED -- use config file instead)"
-       flag.StringVar(&configPath, "config", defaultConfigPath,
-               "`path` to JSON or YAML configuration file")
-       flag.StringVar(&cfg.Listen, "listen", "",
-               "address:port or :port to listen on"+deprecated)
-       flag.BoolVar(&cfg.deprecatedAllowAnonymous, "allow-anonymous", false,
-               "Load an anonymous token from the ARVADOS_API_TOKEN environment variable"+deprecated)
-       flag.StringVar(&cfg.AttachmentOnlyHost, "attachment-only-host", "",
-               "Only serve attachments at the given `host:port`"+deprecated)
-       flag.BoolVar(&cfg.TrustAllContent, "trust-all-content", false,
-               "Serve non-public content from a single origin. Dangerous: read docs before using!"+deprecated)
-       flag.StringVar(&cfg.ManagementToken, "management-token", "",
-               "Authorization token to be included in all health check requests.")
-
-       dumpConfig := flag.Bool("dump-config", false,
-               "write current configuration to stdout and exit")
-       flag.Usage = usage
-       flag.Parse()
-
-       if err := config.LoadFile(cfg, configPath); err != nil {
-               if h := os.Getenv("ARVADOS_API_HOST"); h != "" && configPath == defaultConfigPath {
-                       log.Printf("DEPRECATED: Using ARVADOS_API_HOST environment variable. Use config file instead.")
-                       cfg.Client.APIHost = h
-               } else {
-                       log.Fatal(err)
-               }
-       }
-       if cfg.deprecatedAllowAnonymous {
-               log.Printf("DEPRECATED: Using -allow-anonymous command line flag with ARVADOS_API_TOKEN environment variable. Use config file instead.")
-               cfg.AnonymousTokens = []string{os.Getenv("ARVADOS_API_TOKEN")}
-       }
-
-       if *dumpConfig {
-               log.Fatal(config.DumpAndExit(cfg))
+func newHandler(ctx context.Context, cluster *arvados.Cluster, token string, reg *prometheus.Registry) (*handler, error) {
+       logger := ctxlog.FromContext(ctx)
+       if ext := ".txt"; mime.TypeByExtension(ext) == "" {
+               logger.Warnf("cannot look up MIME type for %q -- this probably means /etc/mime.types is missing -- clients will see incorrect content types", ext)
        }
 
-       os.Setenv("ARVADOS_API_HOST", cfg.Client.APIHost)
-       srv := &server{Config: cfg}
-       if err := srv.Start(); err != nil {
-               log.Fatal(err)
-       }
-       if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
-               log.Printf("Error notifying init daemon: %v", err)
-       }
-       log.Println("Listening at", srv.Addr)
-       if err := srv.Wait(); err != nil {
-               log.Fatal(err)
-       }
+       keepclient.RefreshServiceDiscoveryOnSIGHUP()
+       os.Setenv("ARVADOS_API_HOST", cluster.Services.Controller.ExternalURL.Host)
+       return &handler{
+               Cluster: cluster,
+               Cache: cache{
+                       cluster:  cluster,
+                       logger:   logger,
+                       registry: reg,
+               },
+       }, nil
 }