diff --git a/ocis-pkg/config/config.go b/ocis-pkg/config/config.go index 649013b6e23..a86445e6043 100644 --- a/ocis-pkg/config/config.go +++ b/ocis-pkg/config/config.go @@ -9,6 +9,7 @@ import ( authbasic "github.com/owncloud/ocis/v2/services/auth-basic/pkg/config" authbearer "github.com/owncloud/ocis/v2/services/auth-bearer/pkg/config" authmachine "github.com/owncloud/ocis/v2/services/auth-machine/pkg/config" + experimental "github.com/owncloud/ocis/v2/services/experimental/pkg/config" frontend "github.com/owncloud/ocis/v2/services/frontend/pkg/config" gateway "github.com/owncloud/ocis/v2/services/gateway/pkg/config" graphExplorer "github.com/owncloud/ocis/v2/services/graph-explorer/pkg/config" @@ -105,4 +106,5 @@ type Config struct { Web *web.Config `yaml:"web"` WebDAV *webdav.Config `yaml:"webdav"` Search *search.Config `yaml:"search"` + Experimental *experimental.Config `yaml:"experimental"` } diff --git a/ocis-pkg/config/defaultconfig.go b/ocis-pkg/config/defaultconfig.go index 68b7cada396..f81d1533d21 100644 --- a/ocis-pkg/config/defaultconfig.go +++ b/ocis-pkg/config/defaultconfig.go @@ -7,6 +7,7 @@ import ( authbasic "github.com/owncloud/ocis/v2/services/auth-basic/pkg/config/defaults" authbearer "github.com/owncloud/ocis/v2/services/auth-bearer/pkg/config/defaults" authmachine "github.com/owncloud/ocis/v2/services/auth-machine/pkg/config/defaults" + experimental "github.com/owncloud/ocis/v2/services/experimental/pkg/config/defaults" frontend "github.com/owncloud/ocis/v2/services/frontend/pkg/config/defaults" gateway "github.com/owncloud/ocis/v2/services/gateway/pkg/config/defaults" graphExplorer "github.com/owncloud/ocis/v2/services/graph-explorer/pkg/config/defaults" @@ -72,5 +73,6 @@ func DefaultConfig() *Config { Users: users.DefaultConfig(), Web: web.DefaultConfig(), WebDAV: webdav.DefaultConfig(), + Experimental: experimental.DefaultConfig(), } } diff --git a/ocis/pkg/command/experimental.go b/ocis/pkg/command/experimental.go new file mode 100644 index 00000000000..03f872f1737 --- /dev/null +++ b/ocis/pkg/command/experimental.go @@ -0,0 +1,33 @@ +package command + +import ( + "fmt" + + "github.com/owncloud/ocis/v2/ocis-pkg/config" + "github.com/owncloud/ocis/v2/ocis-pkg/config/parser" + "github.com/owncloud/ocis/v2/ocis/pkg/command/helper" + "github.com/owncloud/ocis/v2/ocis/pkg/register" + "github.com/owncloud/ocis/v2/services/experimental/pkg/command" + "github.com/urfave/cli/v2" +) + +// ExperimentalCommand is the entrypoint for the experimental command. +func ExperimentalCommand(cfg *config.Config) *cli.Command { + return &cli.Command{ + Name: cfg.Experimental.Service.Name, + Usage: helper.SubcommandDescription(cfg.Experimental.Service.Name), + Category: "services", + Before: func(c *cli.Context) error { + if err := parser.ParseConfig(cfg, true); err != nil { + fmt.Printf("%v", err) + } + cfg.Experimental.Commons = cfg.Commons + return nil + }, + Subcommands: command.GetCommands(cfg.Experimental), + } +} + +func init() { + register.AddCommand(ExperimentalCommand) +} diff --git a/ocis/pkg/runtime/service/service.go b/ocis/pkg/runtime/service/service.go index 64714712036..8d21a0f3962 100644 --- a/ocis/pkg/runtime/service/service.go +++ b/ocis/pkg/runtime/service/service.go @@ -25,6 +25,7 @@ import ( authbasic "github.com/owncloud/ocis/v2/services/auth-basic/pkg/command" authbearer "github.com/owncloud/ocis/v2/services/auth-bearer/pkg/command" authmachine "github.com/owncloud/ocis/v2/services/auth-machine/pkg/command" + experimental "github.com/owncloud/ocis/v2/services/experimental/pkg/command" frontend "github.com/owncloud/ocis/v2/services/frontend/pkg/command" gateway "github.com/owncloud/ocis/v2/services/gateway/pkg/command" graphExplorer "github.com/owncloud/ocis/v2/services/graph-explorer/pkg/command" @@ -131,6 +132,7 @@ func NewService(options ...Option) (*Service, error) { s.ServicesRegistry[opts.Config.Notifications.Service.Name] = notifications.NewSutureService s.ServicesRegistry[opts.Config.Search.Service.Name] = search.NewSutureService s.ServicesRegistry[opts.Config.Postprocessing.Service.Name] = postprocessing.NewSutureService + s.ServicesRegistry[opts.Config.Experimental.Service.Name] = experimental.NewSutureService // populate delayed services s.Delayed[opts.Config.Sharing.Service.Name] = sharing.NewSutureService @@ -268,7 +270,7 @@ func (s *Service) generateRunSet(cfg *ociscfg.Config) { } // List running processes for the Service Controller. -func (s *Service) List(args struct{}, reply *string) error { +func (s *Service) List(_ struct{}, reply *string) error { tableString := &strings.Builder{} table := tablewriter.NewWriter(tableString) table.SetHeader([]string{"Extension"}) diff --git a/services/experimental/pkg/command/health.go b/services/experimental/pkg/command/health.go new file mode 100644 index 00000000000..f294511515c --- /dev/null +++ b/services/experimental/pkg/command/health.go @@ -0,0 +1,58 @@ +package command + +import ( + "fmt" + "net/http" + + "github.com/owncloud/ocis/v2/services/experimental/pkg/config" + "github.com/owncloud/ocis/v2/services/experimental/pkg/config/parser" + "github.com/owncloud/ocis/v2/services/experimental/pkg/logging" + "github.com/urfave/cli/v2" +) + +// Health is the entrypoint for the health command. +func Health(cfg *config.Config) *cli.Command { + return &cli.Command{ + Name: "health", + Usage: "check health status", + Category: "info", + Before: func(c *cli.Context) error { + err := parser.ParseConfig(cfg) + if err != nil { + fmt.Printf("%v", err) + } + return err + }, + Action: func(c *cli.Context) error { + logger := logging.Configure(cfg.Service.Name, cfg.Log) + + resp, err := http.Get( + fmt.Sprintf( + "http://%s/healthz", + cfg.Debug.Addr, + ), + ) + + if err != nil { + logger.Fatal(). + Err(err). + Msg("Failed to request health check") + return nil + } + + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + logger.Fatal(). + Int("code", resp.StatusCode). + Msg("Health seems to be in bad state") + } + + logger.Debug(). + Int("code", resp.StatusCode). + Msg("Health got a good state") + + return nil + }, + } +} diff --git a/services/experimental/pkg/command/root.go b/services/experimental/pkg/command/root.go new file mode 100644 index 00000000000..60c5d0814b6 --- /dev/null +++ b/services/experimental/pkg/command/root.go @@ -0,0 +1,48 @@ +package command + +import ( + "context" + "github.com/owncloud/ocis/v2/ocis-pkg/clihelper" + ociscfg "github.com/owncloud/ocis/v2/ocis-pkg/config" + "github.com/owncloud/ocis/v2/services/experimental/pkg/config" + "github.com/thejerf/suture/v4" + "github.com/urfave/cli/v2" + "os" +) + +// GetCommands provides all commands for this service +func GetCommands(cfg *config.Config) cli.Commands { + return []*cli.Command{ + Server(cfg), + Health(cfg), + Version(cfg), + } +} + +// Execute is the entry point for the ocis-webdav command. +func Execute(cfg *config.Config) error { + app := clihelper.DefaultApp(&cli.App{ + Name: "experimental", + Usage: "Serve Experimental for oCIS", + Commands: GetCommands(cfg), + }) + return app.Run(os.Args) +} + +// SutureService allows for the web command to be embedded and supervised by a suture supervisor tree. +type SutureService struct { + cfg *config.Config +} + +// NewSutureService creates a new web.SutureService +func NewSutureService(cfg *ociscfg.Config) suture.Service { + cfg.Experimental.Commons = cfg.Commons + return SutureService{ + cfg: cfg.Experimental, + } +} + +func (s SutureService) Serve(ctx context.Context) error { + s.cfg.Context = ctx + return Execute(s.cfg) +} diff --git a/services/experimental/pkg/command/server.go b/services/experimental/pkg/command/server.go new file mode 100644 index 00000000000..6a2d514607d --- /dev/null +++ b/services/experimental/pkg/command/server.go @@ -0,0 +1,102 @@ +package command + +import ( + "context" + "fmt" + "os" + + "github.com/oklog/run" + "github.com/owncloud/ocis/v2/services/experimental/pkg/config" + "github.com/owncloud/ocis/v2/services/experimental/pkg/config/parser" + "github.com/owncloud/ocis/v2/services/experimental/pkg/logging" + "github.com/owncloud/ocis/v2/services/experimental/pkg/server/debug" + "github.com/owncloud/ocis/v2/services/experimental/pkg/server/http" + "github.com/urfave/cli/v2" +) + +// Server is the entrypoint for the server command. +func Server(cfg *config.Config) *cli.Command { + return &cli.Command{ + Name: "server", + Usage: fmt.Sprintf("start %s extension without runtime (unsupervised mode)", cfg.Service.Name), + Category: "server", + Before: func(c *cli.Context) error { + err := parser.ParseConfig(cfg) + if err != nil { + fmt.Printf("%v", err) + os.Exit(1) + } + return err + }, + Action: func(c *cli.Context) error { + logger := logging.Configure(cfg.Service.Name, cfg.Log) + + var ( + gr = run.Group{} + ctx, cancel = func() (context.Context, context.CancelFunc) { + if cfg.Context == nil { + return context.WithCancel(context.Background()) + } + return context.WithCancel(cfg.Context) + }() + ) + + defer cancel() + + { + server, err := http.Server( + http.Logger(logger), + http.Context(ctx), + http.Namespace(cfg.HTTP.Namespace), + http.Config(cfg), + ) + + if err != nil { + logger.Info(). + Err(err). + Str("transport", "http"). + Msg("Failed to initialize server") + + return err + } + + gr.Add(func() error { + err := server.Run() + if err != nil { + logger.Error(). + Err(err). + Str("transport", "http"). + Msg("Failed to start server") + } + return err + }, func(err error) { + logger.Info(). + Str("transport", "http"). + Msg("Shutting down server") + + cancel() + }) + } + + { + server, err := debug.Server( + debug.Logger(logger), + debug.Context(ctx), + debug.Config(cfg), + ) + + if err != nil { + logger.Info().Err(err).Str("transport", "debug").Msg("Failed to initialize server") + return err + } + + gr.Add(server.ListenAndServe, func(_ error) { + _ = server.Shutdown(ctx) + cancel() + }) + } + + return gr.Run() + }, + } +} diff --git a/services/experimental/pkg/command/version.go b/services/experimental/pkg/command/version.go new file mode 100644 index 00000000000..5ff672b6c68 --- /dev/null +++ b/services/experimental/pkg/command/version.go @@ -0,0 +1,50 @@ +package command + +import ( + "fmt" + "os" + + "github.com/owncloud/ocis/v2/ocis-pkg/registry" + "github.com/owncloud/ocis/v2/ocis-pkg/version" + + tw "github.com/olekukonko/tablewriter" + "github.com/owncloud/ocis/v2/services/experimental/pkg/config" + "github.com/urfave/cli/v2" +) + +// Version prints the service version. +func Version(cfg *config.Config) *cli.Command { + return &cli.Command{ + Name: "version", + Usage: "print the version of this binary and the running extension instances", + Category: "info", + Action: func(c *cli.Context) error { + fmt.Println("Version: " + version.GetString()) + fmt.Printf("Compiled: %s\n", version.Compiled()) + fmt.Println("") + + reg := registry.GetRegistry() + services, err := reg.GetService(cfg.HTTP.Namespace + "." + cfg.Service.Name) + if err != nil { + fmt.Println(fmt.Errorf("could not get %s services from the registry: %v", cfg.Service.Name, err)) + return err + } + + if len(services) == 0 { + fmt.Println("No running " + cfg.Service.Name + " service found.") + return nil + } + + table := tw.NewWriter(os.Stdout) + table.SetHeader([]string{"Version", "Address", "Id"}) + table.SetAutoFormatHeaders(false) + for _, s := range services { + for _, n := range s.Nodes { + table.Append([]string{s.Version, n.Address, n.Id}) + } + } + table.Render() + return nil + }, + } +} diff --git a/services/experimental/pkg/config/config.go b/services/experimental/pkg/config/config.go new file mode 100644 index 00000000000..3155a211a36 --- /dev/null +++ b/services/experimental/pkg/config/config.go @@ -0,0 +1,20 @@ +package config + +import ( + "context" + "github.com/owncloud/ocis/v2/ocis-pkg/shared" +) + +// Config combines all available configuration parts. +type Config struct { + Commons *shared.Commons `yaml:"-"` // don't use this directly as configuration for a service + + Service Service `yaml:"-"` + + Log *Log `yaml:"log"` + Debug Debug `yaml:"debug"` + + HTTP HTTP `yaml:"http"` + + Context context.Context `yaml:"-"` +} diff --git a/services/experimental/pkg/config/debug.go b/services/experimental/pkg/config/debug.go new file mode 100644 index 00000000000..1e6872be1a2 --- /dev/null +++ b/services/experimental/pkg/config/debug.go @@ -0,0 +1,9 @@ +package config + +// Debug defines the available debug configuration. +type Debug struct { + Addr string `ocisConfig:"addr" env:"EXPERIMENTAL_DEBUG_ADDR" desc:"Bind address of the debug server, where health, config and debug endpoints will be exposed."` + Token string `ocisConfig:"token" env:"EXPERIMENTAL_DEBUG_TOKEN" desc:"Token to secure the metrics endpoint."` + Pprof bool `ocisConfig:"pprof" env:"EXPERIMENTAL_DEBUG_PPROF" desc:"Enables pprof, which can be used for profiling."` + Zpages bool `ocisConfig:"zpages" env:"EXPERIMENTAL_DEBUG_ZPAGES" desc:"Enables zpages, which can be used for collecting and viewing in-memory traces."` +} diff --git a/services/experimental/pkg/config/defaults/defaultconfig.go b/services/experimental/pkg/config/defaults/defaultconfig.go new file mode 100644 index 00000000000..7c35d1581ae --- /dev/null +++ b/services/experimental/pkg/config/defaults/defaultconfig.go @@ -0,0 +1,54 @@ +package defaults + +import ( + "github.com/owncloud/ocis/v2/services/experimental/pkg/config" + "strings" +) + +func FullDefaultConfig() *config.Config { + cfg := DefaultConfig() + + EnsureDefaults(cfg) + + return cfg +} + +// DefaultConfig sets default service configuration. +func DefaultConfig() *config.Config { + return &config.Config{ + Debug: config.Debug{ + Addr: "127.0.0.1:9181", + Token: "", + }, + HTTP: config.HTTP{ + Addr: "127.0.0.1:9180", + Namespace: "com.owncloud.experimental", + Root: "/experimental", + }, + Service: config.Service{ + Name: "experimental", + }, + } +} + +// EnsureDefaults ensures that all default values are applied. +func EnsureDefaults(cfg *config.Config) { + // provide with defaults for shared logging, since we need a valid destination address for "envdecode". + if cfg.Log == nil && cfg.Commons != nil && cfg.Commons.Log != nil { + cfg.Log = &config.Log{ + Level: cfg.Commons.Log.Level, + Pretty: cfg.Commons.Log.Pretty, + Color: cfg.Commons.Log.Color, + File: cfg.Commons.Log.File, + } + } else if cfg.Log == nil { + cfg.Log = &config.Log{} + } +} + +// Sanitize config +func Sanitize(cfg *config.Config) { + if cfg.HTTP.Root != "/" { + cfg.HTTP.Root = strings.TrimSuffix(cfg.HTTP.Root, "/") + } +} diff --git a/services/experimental/pkg/config/http.go b/services/experimental/pkg/config/http.go new file mode 100644 index 00000000000..3a23ade3940 --- /dev/null +++ b/services/experimental/pkg/config/http.go @@ -0,0 +1,8 @@ +package config + +// HTTP defines the available http configuration. +type HTTP struct { + Addr string `yaml:"addr" env:"EXPERIMENTAL_HTTP_ADDR" desc:"The bind address of the HTTP service."` + Namespace string `yaml:"-"` + Root string `yaml:"root" env:"EXPERIMENTAL_HTTP_ROOT" desc:"Subdirectory that serves as the root for this HTTP service."` +} diff --git a/services/experimental/pkg/config/log.go b/services/experimental/pkg/config/log.go new file mode 100644 index 00000000000..2a9304c9dfa --- /dev/null +++ b/services/experimental/pkg/config/log.go @@ -0,0 +1,9 @@ +package config + +// Log defines the available log configuration. +type Log struct { + Level string `mapstructure:"level" env:"OCIS_LOG_LEVEL;EXPERIMENTAL_LOG_LEVEL" desc:"The log level. Valid values are: \"panic\", \"fatal\", \"error\", \"warn\", \"info\", \"debug\", \"trace\"."` + Pretty bool `mapstructure:"pretty" env:"OCIS_LOG_PRETTY;EXPERIMENTAL_LOG_PRETTY" desc:"Activates pretty log output."` + Color bool `mapstructure:"color" env:"OCIS_LOG_COLOR;EXPERIMENTAL_LOG_COLOR" desc:"Activates colorized log output."` + File string `mapstructure:"file" env:"OCIS_LOG_FILE;EXPERIMENTAL_LOG_FILE" desc:"The path to the log file. Activates logging to this file if set."` +} diff --git a/services/experimental/pkg/config/parser/parse.go b/services/experimental/pkg/config/parser/parse.go new file mode 100644 index 00000000000..9e95b47b39b --- /dev/null +++ b/services/experimental/pkg/config/parser/parse.go @@ -0,0 +1,37 @@ +package parser + +import ( + "errors" + + ociscfg "github.com/owncloud/ocis/v2/ocis-pkg/config" + "github.com/owncloud/ocis/v2/services/experimental/pkg/config" + "github.com/owncloud/ocis/v2/services/experimental/pkg/config/defaults" + + "github.com/owncloud/ocis/v2/ocis-pkg/config/envdecode" +) + +// ParseConfig loads configuration from known paths. +func ParseConfig(cfg *config.Config) error { + _, err := ociscfg.BindSourcesToStructs(cfg.Service.Name, cfg) + if err != nil { + return err + } + + defaults.EnsureDefaults(cfg) + + // load all env variables relevant to the config in the current context. + if err := envdecode.Decode(cfg); err != nil { + // no environment variable set for this config is an expected "error" + if !errors.Is(err, envdecode.ErrNoTargetFieldsAreSet) { + return err + } + } + + defaults.Sanitize(cfg) + + return Validate(cfg) +} + +func Validate(_ *config.Config) error { + return nil +} diff --git a/services/experimental/pkg/config/service.go b/services/experimental/pkg/config/service.go new file mode 100644 index 00000000000..c019b73046e --- /dev/null +++ b/services/experimental/pkg/config/service.go @@ -0,0 +1,6 @@ +package config + +// Service defines the available service configuration. +type Service struct { + Name string `ocisConfig:"-" yaml:"-"` +} diff --git a/services/experimental/pkg/logging/logging.go b/services/experimental/pkg/logging/logging.go new file mode 100644 index 00000000000..5f7baebe8c2 --- /dev/null +++ b/services/experimental/pkg/logging/logging.go @@ -0,0 +1,17 @@ +package logging + +import ( + "github.com/owncloud/ocis/v2/ocis-pkg/log" + "github.com/owncloud/ocis/v2/services/experimental/pkg/config" +) + +// LoggerFromConfig initializes a service-specific logger instance. +func Configure(name string, cfg *config.Log) log.Logger { + return log.NewLogger( + log.Name(name), + log.Level(cfg.Level), + log.Pretty(cfg.Pretty), + log.Color(cfg.Color), + log.File(cfg.File), + ) +} diff --git a/services/experimental/pkg/server/debug/option.go b/services/experimental/pkg/server/debug/option.go new file mode 100644 index 00000000000..a0b372e3bf0 --- /dev/null +++ b/services/experimental/pkg/server/debug/option.go @@ -0,0 +1,50 @@ +package debug + +import ( + "context" + + "github.com/owncloud/ocis/v2/ocis-pkg/log" + "github.com/owncloud/ocis/v2/services/experimental/pkg/config" +) + +// Option defines a single option function. +type Option func(o *Options) + +// Options defines the available options for this package. +type Options struct { + Logger log.Logger + Context context.Context + Config *config.Config +} + +// newOptions initializes the available default options. +func newOptions(opts ...Option) Options { + opt := Options{} + + for _, o := range opts { + o(&opt) + } + + return opt +} + +// Logger provides a function to set the logger option. +func Logger(val log.Logger) Option { + return func(o *Options) { + o.Logger = val + } +} + +// Context provides a function to set the context option. +func Context(val context.Context) Option { + return func(o *Options) { + o.Context = val + } +} + +// Config provides a function to set the config option. +func Config(val *config.Config) Option { + return func(o *Options) { + o.Config = val + } +} diff --git a/services/experimental/pkg/server/debug/server.go b/services/experimental/pkg/server/debug/server.go new file mode 100644 index 00000000000..ef580d8d7a3 --- /dev/null +++ b/services/experimental/pkg/server/debug/server.go @@ -0,0 +1,59 @@ +package debug + +import ( + "io" + "net/http" + + "github.com/owncloud/ocis/v2/ocis-pkg/service/debug" + "github.com/owncloud/ocis/v2/ocis-pkg/version" + "github.com/owncloud/ocis/v2/services/experimental/pkg/config" +) + +// Server initializes the debug service and server. +func Server(opts ...Option) (*http.Server, error) { + options := newOptions(opts...) + + return debug.NewService( + debug.Logger(options.Logger), + debug.Name(options.Config.Service.Name), + debug.Version(version.GetString()), + debug.Address(options.Config.Debug.Addr), + debug.Token(options.Config.Debug.Token), + debug.Pprof(options.Config.Debug.Pprof), + debug.Zpages(options.Config.Debug.Zpages), + debug.Health(health(options.Config)), + debug.Ready(ready(options.Config)), + ), nil +} + +// health implements the health check. +func health(_ *config.Config) func(http.ResponseWriter, *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain") + w.WriteHeader(http.StatusOK) + + // TODO: check if services are up and running + + _, err := io.WriteString(w, http.StatusText(http.StatusOK)) + // io.WriteString should not fail but if it does we want to know. + if err != nil { + panic(err) + } + } +} + +// ready implements the ready check. +func ready(_ *config.Config) func(http.ResponseWriter, *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain") + w.WriteHeader(http.StatusOK) + + // TODO: check if services are up and running + + _, err := io.WriteString(w, http.StatusText(http.StatusOK)) + // io.WriteString should not fail but if it does we want to know. + if err != nil { + panic(err) + } + } +} diff --git a/services/experimental/pkg/server/http/option.go b/services/experimental/pkg/server/http/option.go new file mode 100644 index 00000000000..6765fb4653e --- /dev/null +++ b/services/experimental/pkg/server/http/option.go @@ -0,0 +1,58 @@ +package http + +import ( + "context" + + "github.com/owncloud/ocis/v2/ocis-pkg/log" + "github.com/owncloud/ocis/v2/services/experimental/pkg/config" +) + +// Option defines a single option function. +type Option func(o *Options) + +// Options defines the available options for this package. +type Options struct { + Logger log.Logger + Context context.Context + Config *config.Config + Namespace string +} + +// newOptions initializes the available default options. +func newOptions(opts ...Option) Options { + opt := Options{} + + for _, o := range opts { + o(&opt) + } + + return opt +} + +// Logger provides a function to set the logger option. +func Logger(val log.Logger) Option { + return func(o *Options) { + o.Logger = val + } +} + +// Context provides a function to set the context option. +func Context(val context.Context) Option { + return func(o *Options) { + o.Context = val + } +} + +// Config provides a function to set the config option. +func Config(val *config.Config) Option { + return func(o *Options) { + o.Config = val + } +} + +// Namespace provides a function to set the Namespace option. +func Namespace(val string) Option { + return func(o *Options) { + o.Namespace = val + } +} diff --git a/services/experimental/pkg/server/http/server.go b/services/experimental/pkg/server/http/server.go new file mode 100644 index 00000000000..21660be7d43 --- /dev/null +++ b/services/experimental/pkg/server/http/server.go @@ -0,0 +1,45 @@ +package http + +import ( + chimiddleware "github.com/go-chi/chi/v5/middleware" + "github.com/owncloud/ocis/v2/ocis-pkg/middleware" + "github.com/owncloud/ocis/v2/ocis-pkg/service/http" + "github.com/owncloud/ocis/v2/ocis-pkg/version" + svc "github.com/owncloud/ocis/v2/services/experimental/pkg/service/http/v0" + "go-micro.dev/v4" +) + +// Server initializes the http service and server. +func Server(opts ...Option) (http.Service, error) { + options := newOptions(opts...) + + service := http.NewService( + http.Logger(options.Logger), + http.Namespace(options.Config.HTTP.Namespace), + http.Name("experimental"), + http.Version(version.GetString()), + http.Address(options.Config.HTTP.Addr), + http.Context(options.Context), + ) + + handle := svc.NewService( + svc.Logger(options.Logger), + svc.Config(options.Config), + svc.Middleware( + chimiddleware.RequestID, + middleware.Version( + "experimental", + version.GetString(), + ), + middleware.Logger( + options.Logger, + ), + ), + ) + + if err := micro.RegisterHandler(service.Server(), handle); err != nil { + return http.Service{}, err + } + + return service, nil +} diff --git a/services/experimental/pkg/service/http/v0/option.go b/services/experimental/pkg/service/http/v0/option.go new file mode 100644 index 00000000000..e8ce26f0888 --- /dev/null +++ b/services/experimental/pkg/service/http/v0/option.go @@ -0,0 +1,50 @@ +package svc + +import ( + "net/http" + + "github.com/owncloud/ocis/v2/ocis-pkg/log" + "github.com/owncloud/ocis/v2/services/experimental/pkg/config" +) + +// Option defines a single option function. +type Option func(o *Options) + +// Options defines the available options for this package. +type Options struct { + Logger log.Logger + Config *config.Config + Middleware []func(http.Handler) http.Handler +} + +// newOptions initializes the available default options. +func newOptions(opts ...Option) Options { + opt := Options{} + + for _, o := range opts { + o(&opt) + } + + return opt +} + +// Logger provides a function to set the logger option. +func Logger(val log.Logger) Option { + return func(o *Options) { + o.Logger = val + } +} + +// Config provides a function to set the config option. +func Config(val *config.Config) Option { + return func(o *Options) { + o.Config = val + } +} + +// Middleware provides a function to set the middleware option. +func Middleware(val ...func(http.Handler) http.Handler) Option { + return func(o *Options) { + o.Middleware = val + } +} diff --git a/services/experimental/pkg/service/http/v0/service.go b/services/experimental/pkg/service/http/v0/service.go new file mode 100644 index 00000000000..0732618fcee --- /dev/null +++ b/services/experimental/pkg/service/http/v0/service.go @@ -0,0 +1,41 @@ +package svc + +import ( + "github.com/go-chi/chi/v5" + "github.com/owncloud/ocis/v2/ocis-pkg/service/grpc" + searchsvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/search/v0" + "github.com/owncloud/ocis/v2/services/experimental/pkg/tags" + "net/http" +) + +// NewService returns a service implementation for Service. +func NewService(opts ...Option) Experimental { + options := newOptions(opts...) + + m := chi.NewMux() + m.Use(options.Middleware...) + + svc := Experimental{ + mux: m, + } + + m.Route(options.Config.HTTP.Root, func(r chi.Router) { + tags.NewTagsService( + r, + searchsvc.NewSearchProviderService("com.owncloud.api.search", grpc.DefaultClient), + options.Logger, + ) + }) + + return svc +} + +// Experimental implements the business logic for Service. +type Experimental struct { + mux *chi.Mux +} + +// ServeHTTP implements the Service interface. +func (s Experimental) ServeHTTP(w http.ResponseWriter, r *http.Request) { + s.mux.ServeHTTP(w, r) +} diff --git a/services/experimental/pkg/tags/tags.go b/services/experimental/pkg/tags/tags.go new file mode 100644 index 00000000000..a2cbe83f64c --- /dev/null +++ b/services/experimental/pkg/tags/tags.go @@ -0,0 +1,69 @@ +package tags + +import ( + "encoding/json" + revactx "github.com/cs3org/reva/v2/pkg/ctx" + "github.com/cs3org/reva/v2/pkg/tags" + "github.com/go-chi/chi/v5" + "github.com/owncloud/ocis/v2/ocis-pkg/log" + searchsvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/search/v0" + "go-micro.dev/v4/metadata" + "net/http" +) + +type tagsService struct { + r chi.Router + logger log.Logger + searchClient searchsvc.SearchProviderService +} + +// NewTagsService bootstraps the tags service +func NewTagsService(r chi.Router, searchClient searchsvc.SearchProviderService, logger log.Logger) { + svc := tagsService{ + logger: logger, + searchClient: searchClient, + } + + r.Get("/tags", svc.GetTags) +} + +// GetTags lists all available tags as json response. +func (s *tagsService) GetTags(w http.ResponseWriter, r *http.Request) { + th := r.Header.Get(revactx.TokenHeader) + ctx := revactx.ContextSetToken(r.Context(), th) + ctx = metadata.Set(ctx, revactx.TokenHeader, th) + sr, err := s.searchClient.Search(ctx, &searchsvc.SearchRequest{ + Query: "Tags:*", + PageSize: -1, + }) + if err != nil { + s.logger.Error().Err(err).Msg("Could not search for tags") + w.WriteHeader(http.StatusInternalServerError) + return + } + + t := tags.FromList("") + for _, match := range sr.Matches { + for _, tag := range match.Entity.Tags { + t.AddList(tag) + } + } + + jm, err := json.Marshal(struct { + Tags []string `json:"tags"` + }{ + Tags: t.AsSlice(), + }) + if err != nil { + s.logger.Error().Err(err).Msg("Could not read tags") + w.WriteHeader(http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + if _, err = w.Write(jm); err != nil { + s.logger.Error().Err(err).Msg("Could not write tags") + w.WriteHeader(http.StatusInternalServerError) + } +} diff --git a/services/proxy/pkg/config/defaults/defaultconfig.go b/services/proxy/pkg/config/defaults/defaultconfig.go index 1c6f8489348..ef5bcb1ea5b 100644 --- a/services/proxy/pkg/config/defaults/defaultconfig.go +++ b/services/proxy/pkg/config/defaults/defaultconfig.go @@ -172,6 +172,10 @@ func DefaultPolicies() []config.Policy { Endpoint: "/graph-explorer", Backend: "http://localhost:9135", }, + { + Endpoint: "/experimental", + Backend: "http://localhost:9180", + }, { Endpoint: "/api/v0/settings", Backend: "http://localhost:9190", diff --git a/services/search/pkg/engine/bleve.go b/services/search/pkg/engine/bleve.go index 5fa49f850ce..015a3c72805 100644 --- a/services/search/pkg/engine/bleve.go +++ b/services/search/pkg/engine/bleve.go @@ -115,10 +115,16 @@ func (b *Bleve) Search(_ context.Context, sir *searchService.SearchIndexRequest) ) bleveReq := bleve.NewSearchRequest(q) - bleveReq.Size = 200 - if sir.PageSize > 0 { + + switch { + case sir.PageSize == -1: + bleveReq.Size = math.MaxInt + case sir.PageSize == 0: + bleveReq.Size = 200 + default: bleveReq.Size = int(sir.PageSize) } + bleveReq.Fields = []string{"*"} res, err := b.index.Search(bleveReq) if err != nil { @@ -150,7 +156,7 @@ func (b *Bleve) Search(_ context.Context, sir *searchService.SearchIndexRequest) Type: uint64(getValue[float64](hit.Fields, "Type")), MimeType: getValue[string](hit.Fields, "MimeType"), Deleted: getValue[bool](hit.Fields, "Deleted"), - Tags: getValue[[]string](hit.Fields, "Tags"), + Tags: getSliceValue[string](hit.Fields, "Tags"), }, } @@ -263,7 +269,7 @@ func (b *Bleve) getResource(id string) (*Resource, error) { Size: uint64(getValue[float64](fields, "Size")), Mtime: getValue[string](fields, "Mtime"), MimeType: getValue[string](fields, "MimeType"), - Tags: getValue[[]string](fields, "Tags"), + Tags: getSliceValue[string](fields, "Tags"), }, }, nil } diff --git a/services/search/pkg/engine/engine.go b/services/search/pkg/engine/engine.go index 97184518dd3..4f1890790a7 100644 --- a/services/search/pkg/engine/engine.go +++ b/services/search/pkg/engine/engine.go @@ -55,3 +55,16 @@ func getValue[T any](m map[string]interface{}, key string) (out T) { return } + +func getSliceValue[T any](m map[string]interface{}, key string) (out []T) { + for _, iv := range getValue[[]interface{}](m, key) { + cv, ok := iv.(T) + if !ok { + continue + } + + out = append(out, cv) + } + + return +} diff --git a/services/search/pkg/search/provider.go b/services/search/pkg/search/provider.go index 0ea5f583dcd..17770e6bb23 100644 --- a/services/search/pkg/search/provider.go +++ b/services/search/pkg/search/provider.go @@ -159,7 +159,7 @@ func (p *Provider) Search(ctx context.Context, req *searchsvc.SearchRequest) (*s if limit == 0 { limit = 200 } - if int32(len(matches)) > limit { + if int32(len(matches)) > limit && limit != -1 { matches = matches[0:limit] } diff --git a/services/search/pkg/server/grpc/option.go b/services/search/pkg/server/grpc/option.go index 1aec67b0033..577a862d6af 100644 --- a/services/search/pkg/server/grpc/option.go +++ b/services/search/pkg/server/grpc/option.go @@ -6,7 +6,7 @@ import ( "github.com/owncloud/ocis/v2/ocis-pkg/log" "github.com/owncloud/ocis/v2/services/search/pkg/config" "github.com/owncloud/ocis/v2/services/search/pkg/metrics" - svc "github.com/owncloud/ocis/v2/services/search/pkg/service/v0" + svc "github.com/owncloud/ocis/v2/services/search/pkg/service/grpc/v0" "github.com/urfave/cli/v2" ) diff --git a/services/search/pkg/server/grpc/server.go b/services/search/pkg/server/grpc/server.go index 28bad68a3ce..1b7474cd024 100644 --- a/services/search/pkg/server/grpc/server.go +++ b/services/search/pkg/server/grpc/server.go @@ -4,7 +4,7 @@ import ( "github.com/owncloud/ocis/v2/ocis-pkg/service/grpc" "github.com/owncloud/ocis/v2/ocis-pkg/version" searchsvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/search/v0" - svc "github.com/owncloud/ocis/v2/services/search/pkg/service/v0" + svc "github.com/owncloud/ocis/v2/services/search/pkg/service/grpc/v0" ) // Server initializes a new go-micro service ready to run diff --git a/services/search/pkg/service/v0/option.go b/services/search/pkg/service/grpc/v0/option.go similarity index 100% rename from services/search/pkg/service/v0/option.go rename to services/search/pkg/service/grpc/v0/option.go diff --git a/services/search/pkg/service/v0/service.go b/services/search/pkg/service/grpc/v0/service.go similarity index 98% rename from services/search/pkg/service/v0/service.go rename to services/search/pkg/service/grpc/v0/service.go index 811e541aae3..b7fd750e287 100644 --- a/services/search/pkg/service/v0/service.go +++ b/services/search/pkg/service/grpc/v0/service.go @@ -118,7 +118,7 @@ func (s Service) Search(ctx context.Context, in *searchsvc.SearchRequest, out *s } // IndexSpace (re)indexes all resources of a given space. -func (s Service) IndexSpace(ctx context.Context, in *searchsvc.IndexSpaceRequest, out *searchsvc.IndexSpaceResponse) error { +func (s Service) IndexSpace(ctx context.Context, in *searchsvc.IndexSpaceRequest, _ *searchsvc.IndexSpaceResponse) error { _, err := s.provider.IndexSpace(ctx, in) return err }