fix graph and graph-explorer

Signed-off-by: Jörn Friedrich Dreyer <jfd@butonic.de>
This commit is contained in:
Jörn Friedrich Dreyer committed 2021-03-15 15:17:29 +00:00
1 parent 5594c142dd
commit 9fa77a27ba
18 files changed
+254 -200

No files matched your search

+2 -4
View File
@@ -5,15 +5,13 @@ import (
"os" "os"
"strings" "strings"
"github.com/owncloud/ocis/ocis-pkg/sync"
"github.com/owncloud/ocis/accounts/pkg/flagset"
"github.com/micro/cli/v2" "github.com/micro/cli/v2"
"github.com/owncloud/ocis/accounts/pkg/config" "github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/accounts/pkg/flagset"
"github.com/owncloud/ocis/accounts/pkg/version" "github.com/owncloud/ocis/accounts/pkg/version"
ociscfg "github.com/owncloud/ocis/ocis-pkg/config" ociscfg "github.com/owncloud/ocis/ocis-pkg/config"
"github.com/owncloud/ocis/ocis-pkg/log" "github.com/owncloud/ocis/ocis-pkg/log"
"github.com/owncloud/ocis/ocis-pkg/sync"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/thejerf/suture/v4" "github.com/thejerf/suture/v4"
) )
+2 -1
View File
@@ -4,10 +4,11 @@ import (
"os" "os"
"github.com/owncloud/ocis/graph-explorer/pkg/command" "github.com/owncloud/ocis/graph-explorer/pkg/command"
"github.com/owncloud/ocis/graph-explorer/pkg/config"
) )
func main() { func main() {
if err := command.Execute(); err != nil { if err := command.Execute(config.New()); err != nil {
os.Exit(1) os.Exit(1)
} }
} }
+76 -42
View File
@@ -1,6 +1,7 @@
package command package command
import ( import (
"context"
"os" "os"
"strings" "strings"
@@ -8,14 +9,15 @@ import (
"github.com/owncloud/ocis/graph-explorer/pkg/config" "github.com/owncloud/ocis/graph-explorer/pkg/config"
"github.com/owncloud/ocis/graph-explorer/pkg/flagset" "github.com/owncloud/ocis/graph-explorer/pkg/flagset"
"github.com/owncloud/ocis/graph-explorer/pkg/version" "github.com/owncloud/ocis/graph-explorer/pkg/version"
ociscfg "github.com/owncloud/ocis/ocis-pkg/config"
"github.com/owncloud/ocis/ocis-pkg/log" "github.com/owncloud/ocis/ocis-pkg/log"
"github.com/owncloud/ocis/ocis-pkg/sync"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/thejerf/suture/v4"
) )
// Execute is the entry point for the graph-explorer command. // Execute is the entry point for the graph-explorer command.
func Execute() error { func Execute(cfg *config.Config) error {
cfg := config.New()
app := &cli.App{ app := &cli.App{
Name: "graph-explorer", Name: "graph-explorer",
Version: version.String, Version: version.String,
@@ -32,45 +34,8 @@ func Execute() error {
Flags: flagset.RootWithConfig(cfg), Flags: flagset.RootWithConfig(cfg),
Before: func(c *cli.Context) error { Before: func(c *cli.Context) error {
logger := NewLogger(cfg) cfg.Server.Version = version.String
return ParseConfig(c, cfg)
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.SetEnvPrefix("GRAPH_EXPLORER")
viper.AutomaticEnv()
if c.IsSet("config-file") {
viper.SetConfigFile(c.String("config-file"))
} else {
viper.SetConfigName("graph-explorer")
viper.AddConfigPath("/etc/ocis")
viper.AddConfigPath("$HOME/.ocis")
viper.AddConfigPath("./config")
}
if err := viper.ReadInConfig(); err != nil {
switch err.(type) {
case viper.ConfigFileNotFoundError:
logger.Info().
Msg("Continue without config")
case viper.UnsupportedConfigError:
logger.Fatal().
Err(err).
Msg("Unsupported config type")
default:
logger.Fatal().
Err(err).
Msg("Failed to read config")
}
}
if err := viper.Unmarshal(&cfg); err != nil {
logger.Fatal().
Err(err).
Msg("Failed to parse config")
}
return nil
}, },
Commands: []*cli.Command{ Commands: []*cli.Command{
@@ -101,3 +66,72 @@ func NewLogger(cfg *config.Config) log.Logger {
log.Color(cfg.Log.Color), log.Color(cfg.Log.Color),
) )
} }
// ParseConfig loads accounts configuration from Viper known paths.
func ParseConfig(c *cli.Context, cfg *config.Config) error {
sync.ParsingViperConfig.Lock()
defer sync.ParsingViperConfig.Unlock()
logger := NewLogger(cfg)
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.SetEnvPrefix("GRAPH_EXPLORER")
viper.AutomaticEnv()
if c.IsSet("config-file") {
viper.SetConfigFile(c.String("config-file"))
} else {
viper.SetConfigName("graph-explorer")
viper.AddConfigPath("/etc/ocis")
viper.AddConfigPath("$HOME/.ocis")
viper.AddConfigPath("./config")
}
if err := viper.ReadInConfig(); err != nil {
switch err.(type) {
case viper.ConfigFileNotFoundError:
logger.Info().
Msg("Continue without config")
case viper.UnsupportedConfigError:
logger.Fatal().
Err(err).
Msg("Unsupported config type")
default:
logger.Fatal().
Err(err).
Msg("Failed to read config")
}
}
if err := viper.Unmarshal(&cfg); err != nil {
logger.Fatal().
Err(err).
Msg("Failed to parse config")
}
return nil
}
// SutureService allows for the graph-explorer command to be embedded and supervised by a suture supervisor tree.
type SutureService struct {
cfg *config.Config
}
// NewSutureService creates a new graph-explorer.SutureService
func NewSutureService(cfg *ociscfg.Config) suture.Service {
if cfg.Mode == 0 {
cfg.GraphExplorer.Supervised = true
}
return SutureService{
cfg: cfg.GraphExplorer,
}
}
func (s SutureService) Serve(ctx context.Context) error {
s.cfg.Context = ctx
if err := Execute(s.cfg); err != nil {
return err
}
return nil
}
+26 -49
View File
@@ -2,8 +2,6 @@ package command
import ( import (
"context" "context"
"os"
"os/signal"
"strings" "strings"
"time" "time"
@@ -19,6 +17,7 @@ import (
"github.com/owncloud/ocis/graph-explorer/pkg/metrics" "github.com/owncloud/ocis/graph-explorer/pkg/metrics"
"github.com/owncloud/ocis/graph-explorer/pkg/server/debug" "github.com/owncloud/ocis/graph-explorer/pkg/server/debug"
"github.com/owncloud/ocis/graph-explorer/pkg/server/http" "github.com/owncloud/ocis/graph-explorer/pkg/server/http"
"github.com/owncloud/ocis/ocis-pkg/sync"
"go.opencensus.io/stats/view" "go.opencensus.io/stats/view"
"go.opencensus.io/trace" "go.opencensus.io/trace"
) )
@@ -29,11 +28,18 @@ func Server(cfg *config.Config) *cli.Command {
Name: "server", Name: "server",
Usage: "Start integrated server", Usage: "Start integrated server",
Flags: flagset.ServerWithConfig(cfg), Flags: flagset.ServerWithConfig(cfg),
Before: func(c *cli.Context) error { Before: func(ctx *cli.Context) error {
logger := NewLogger(cfg)
if cfg.HTTP.Root != "/" { if cfg.HTTP.Root != "/" {
cfg.HTTP.Root = strings.TrimSuffix(cfg.HTTP.Root, "/") cfg.HTTP.Root = strings.TrimSuffix(cfg.HTTP.Root, "/")
} }
// When running on single binary mode the before hook from the root command won't get called. We manually
// call this before hook from ocis command, so the configuration can be loaded.
if !cfg.Supervised {
return ParseConfig(ctx, cfg)
}
logger.Debug().Str("service", "graph-explorer").Msg("ignoring config file parsing when running supervised")
return nil return nil
}, },
Action: func(c *cli.Context) error { Action: func(c *cli.Context) error {
@@ -125,29 +131,30 @@ func Server(cfg *config.Config) *cli.Command {
var ( var (
gr = run.Group{} gr = run.Group{}
ctx, cancel = context.WithCancel(context.Background()) ctx, cancel = func() (context.Context, context.CancelFunc) {
metrics = metrics.New() if cfg.Context == nil {
return context.WithCancel(context.Background())
}
return context.WithCancel(cfg.Context)
}()
mtrcs = metrics.New()
) )
defer cancel() defer cancel()
mtrcs.BuildInfo.WithLabelValues(cfg.Server.Version).Set(1)
{ {
server, err := http.Server( server, err := http.Server(
http.Logger(logger), http.Logger(logger),
http.Context(ctx), http.Context(ctx),
http.Namespace(cfg.HTTP.Namespace), http.Namespace(cfg.HTTP.Namespace),
http.Config(cfg), http.Config(cfg),
http.Metrics(metrics), http.Metrics(mtrcs),
http.Flags(flagset.RootWithConfig(cfg)),
http.Flags(flagset.ServerWithConfig(cfg)),
) )
if err != nil { if err != nil {
logger.Info(). logger.Info().Err(err).Str("transport", "http").Msg("Failed to initialize server")
Err(err).
Str("transport", "http").
Msg("Failed to initialize server")
return err return err
} }
@@ -177,48 +184,18 @@ func Server(cfg *config.Config) *cli.Command {
) )
if err != nil { if err != nil {
logger.Info(). logger.Info().Err(err).Str("transport", "debug").Msg("Failed to initialize server")
Err(err).
Str("transport", "debug").
Msg("Failed to initialize server")
return err return err
} }
gr.Add(func() error { gr.Add(server.ListenAndServe, func(_ error) {
return server.ListenAndServe() _ = server.Shutdown(ctx)
}, func(_ error) { cancel()
ctx, timeout := context.WithTimeout(ctx, 5*time.Second)
defer timeout()
defer cancel()
if err := server.Shutdown(ctx); err != nil {
logger.Info().
Err(err).
Str("transport", "debug").
Msg("Failed to shutdown server")
} else {
logger.Info().
Str("transport", "debug").
Msg("Shutting down server")
}
}) })
} }
{ if !cfg.Supervised {
stop := make(chan os.Signal, 1) sync.Trap(&gr, cancel)
gr.Add(func() error {
signal.Notify(stop, os.Interrupt)
<-stop
return nil
}, func(err error) {
//close(stop)
cancel()
})
} }
return gr.Run() return gr.Run()
+12 -1
View File
@@ -1,5 +1,7 @@
package config package config
import "context"
// Log defines the available logging configuration. // Log defines the available logging configuration.
type Log struct { type Log struct {
Level string Level string
@@ -22,6 +24,12 @@ type HTTP struct {
Namespace string Namespace string
} }
// Server configures a server.
type Server struct {
Version string
Name string
}
// Tracing defines the available tracing configuration. // Tracing defines the available tracing configuration.
type Tracing struct { type Tracing struct {
Enabled bool Enabled bool
@@ -44,9 +52,12 @@ type Config struct {
Log Log Log Log
Debug Debug Debug Debug
HTTP HTTP HTTP HTTP
Server Server
Tracing Tracing Tracing Tracing
GraphExplorer GraphExplorer GraphExplorer GraphExplorer
Supervised bool
Context context.Context
Supervised bool
} }
// New initializes a new configuration with or without defaults. // New initializes a new configuration with or without defaults.
+15 -17
View File
@@ -3,6 +3,7 @@ package flagset
import ( import (
"github.com/micro/cli/v2" "github.com/micro/cli/v2"
"github.com/owncloud/ocis/graph-explorer/pkg/config" "github.com/owncloud/ocis/graph-explorer/pkg/config"
"github.com/owncloud/ocis/ocis-pkg/flags"
) )
// RootWithConfig applies cfg to the root flagset // RootWithConfig applies cfg to the root flagset
@@ -10,20 +11,17 @@ func RootWithConfig(cfg *config.Config) []cli.Flag {
return []cli.Flag{ return []cli.Flag{
&cli.StringFlag{ &cli.StringFlag{
Name: "log-level", Name: "log-level",
Value: "info",
Usage: "Set logging level", Usage: "Set logging level",
EnvVars: []string{"GRAPH_EXPLORER_LOG_LEVEL"}, EnvVars: []string{"GRAPH_EXPLORER_LOG_LEVEL"},
Destination: &cfg.Log.Level, Destination: &cfg.Log.Level,
}, },
&cli.BoolFlag{ &cli.BoolFlag{
Value: true,
Name: "log-pretty", Name: "log-pretty",
Usage: "Enable pretty logging", Usage: "Enable pretty logging",
EnvVars: []string{"GRAPH_EXPLORER_LOG_PRETTY"}, EnvVars: []string{"GRAPH_EXPLORER_LOG_PRETTY"},
Destination: &cfg.Log.Pretty, Destination: &cfg.Log.Pretty,
}, },
&cli.BoolFlag{ &cli.BoolFlag{
Value: true,
Name: "log-color", Name: "log-color",
Usage: "Enable colored logging", Usage: "Enable colored logging",
EnvVars: []string{"GRAPH_EXPLORER_LOG_COLOR"}, EnvVars: []string{"GRAPH_EXPLORER_LOG_COLOR"},
@@ -37,7 +35,7 @@ func HealthWithConfig(cfg *config.Config) []cli.Flag {
return []cli.Flag{ return []cli.Flag{
&cli.StringFlag{ &cli.StringFlag{
Name: "debug-addr", Name: "debug-addr",
Value: "0.0.0.0:9136", Value: flags.OverrideDefaultString(cfg.Debug.Addr, "0.0.0.0:9136"),
Usage: "Address to debug endpoint", Usage: "Address to debug endpoint",
EnvVars: []string{"GRAPH_EXPLORER_DEBUG_ADDR"}, EnvVars: []string{"GRAPH_EXPLORER_DEBUG_ADDR"},
Destination: &cfg.Debug.Addr, Destination: &cfg.Debug.Addr,
@@ -56,42 +54,42 @@ func ServerWithConfig(cfg *config.Config) []cli.Flag {
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: "tracing-type", Name: "tracing-type",
Value: "jaeger", Value: flags.OverrideDefaultString(cfg.Tracing.Type, "jaeger"),
Usage: "Tracing backend type", Usage: "Tracing backend type",
EnvVars: []string{"GRAPH_EXPLORER_TRACING_TYPE"}, EnvVars: []string{"GRAPH_EXPLORER_TRACING_TYPE"},
Destination: &cfg.Tracing.Type, Destination: &cfg.Tracing.Type,
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: "tracing-endpoint", Name: "tracing-endpoint",
Value: "", Value: flags.OverrideDefaultString(cfg.Tracing.Endpoint, ""),
Usage: "Endpoint for the agent", Usage: "Endpoint for the agent",
EnvVars: []string{"GRAPH_EXPLORER_TRACING_ENDPOINT"}, EnvVars: []string{"GRAPH_EXPLORER_TRACING_ENDPOINT"},
Destination: &cfg.Tracing.Endpoint, Destination: &cfg.Tracing.Endpoint,
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: "tracing-collector", Name: "tracing-collector",
Value: "", Value: flags.OverrideDefaultString(cfg.Tracing.Collector, ""),
Usage: "Endpoint for the collector", Usage: "Endpoint for the collector",
EnvVars: []string{"GRAPH_EXPLORER_TRACING_COLLECTOR"}, EnvVars: []string{"GRAPH_EXPLORER_TRACING_COLLECTOR"},
Destination: &cfg.Tracing.Collector, Destination: &cfg.Tracing.Collector,
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: "tracing-service", Name: "tracing-service",
Value: "graph-explorer", Value: flags.OverrideDefaultString(cfg.Tracing.Service, "graph-explorer"),
Usage: "Service name for tracing", Usage: "Service name for tracing",
EnvVars: []string{"GRAPH_EXPLORER_TRACING_SERVICE"}, EnvVars: []string{"GRAPH_EXPLORER_TRACING_SERVICE"},
Destination: &cfg.Tracing.Service, Destination: &cfg.Tracing.Service,
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: "debug-addr", Name: "debug-addr",
Value: "0.0.0.0:9136", Value: flags.OverrideDefaultString(cfg.Debug.Addr, "0.0.0.0:9136"),
Usage: "Address to bind debug server", Usage: "Address to bind debug server",
EnvVars: []string{"GRAPH_EXPLORER_DEBUG_ADDR"}, EnvVars: []string{"GRAPH_EXPLORER_DEBUG_ADDR"},
Destination: &cfg.Debug.Addr, Destination: &cfg.Debug.Addr,
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: "debug-token", Name: "debug-token",
Value: "", Value: flags.OverrideDefaultString(cfg.Debug.Token, ""),
Usage: "Token to grant metrics access", Usage: "Token to grant metrics access",
EnvVars: []string{"GRAPH_EXPLORER_DEBUG_TOKEN"}, EnvVars: []string{"GRAPH_EXPLORER_DEBUG_TOKEN"},
Destination: &cfg.Debug.Token, Destination: &cfg.Debug.Token,
@@ -110,42 +108,42 @@ func ServerWithConfig(cfg *config.Config) []cli.Flag {
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: "http-addr", Name: "http-addr",
Value: "0.0.0.0:9135", Value: flags.OverrideDefaultString(cfg.HTTP.Addr, "0.0.0.0:9135"),
Usage: "Address to bind http server", Usage: "Address to bind http server",
EnvVars: []string{"GRAPH_EXPLORER_HTTP_ADDR"}, EnvVars: []string{"GRAPH_EXPLORER_HTTP_ADDR"},
Destination: &cfg.HTTP.Addr, Destination: &cfg.HTTP.Addr,
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: "http-root", Name: "http-root",
Value: "/", Value: flags.OverrideDefaultString(cfg.HTTP.Root, "/graph-explorer"),
Usage: "Root path of http server", Usage: "Root path of http server",
EnvVars: []string{"GRAPH_EXPLORER_HTTP_ROOT"}, EnvVars: []string{"GRAPH_EXPLORER_HTTP_ROOT"},
Destination: &cfg.HTTP.Root, Destination: &cfg.HTTP.Root,
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: "http-namespace", Name: "http-namespace",
Value: "com.owncloud.web", Value: flags.OverrideDefaultString(cfg.HTTP.Namespace, "com.owncloud.web"),
Usage: "Set the base namespace for the http namespace", Usage: "Set the base namespace for the http namespace",
EnvVars: []string{"GRAPH_EXPLORER_NAMESPACE"}, EnvVars: []string{"GRAPH_EXPLORER_NAMESPACE"},
Destination: &cfg.HTTP.Namespace, Destination: &cfg.HTTP.Namespace,
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: "issuer", Name: "issuer",
Value: "https://localhost:9130", Value: flags.OverrideDefaultString(cfg.GraphExplorer.Issuer, "https://localhost:9200"),
Usage: "Set the OpenID Connect Provider", Usage: "Set the OpenID Connect Provider",
EnvVars: []string{"GRAPH_EXPLORER_ISSUER"}, EnvVars: []string{"GRAPH_EXPLORER_ISSUER", "OCIS_URL"},
Destination: &cfg.GraphExplorer.Issuer, Destination: &cfg.GraphExplorer.Issuer,
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: "client-id", Name: "client-id",
Value: "ocis-explorer.js", Value: flags.OverrideDefaultString(cfg.GraphExplorer.ClientID, "ocis-explorer.js"),
Usage: "Set the OpenID Client ID to send to the issuer", Usage: "Set the OpenID Client ID to send to the issuer",
EnvVars: []string{"GRAPH_EXPLORER_CLIENT_ID"}, EnvVars: []string{"GRAPH_EXPLORER_CLIENT_ID"},
Destination: &cfg.GraphExplorer.ClientID, Destination: &cfg.GraphExplorer.ClientID,
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: "graph-url", Name: "graph-url",
Value: "http://localhost:9120", Value: flags.OverrideDefaultString(cfg.GraphExplorer.GraphURL, "https://localhost:9200/graph"),
Usage: "Set the url to the graph api service", Usage: "Set the url to the graph api service",
EnvVars: []string{"GRAPH_EXPLORER_GRAPH_URL"}, EnvVars: []string{"GRAPH_EXPLORER_GRAPH_URL"},
Destination: &cfg.GraphExplorer.GraphURL, Destination: &cfg.GraphExplorer.GraphURL,
+11 -10
View File
@@ -1,5 +1,7 @@
package metrics package metrics
import "github.com/prometheus/client_golang/prometheus"
var ( var (
// Namespace defines the namespace for the defines metrics. // Namespace defines the namespace for the defines metrics.
Namespace = "ocis" Namespace = "ocis"
@@ -11,22 +13,21 @@ var (
// Metrics defines the available metrics of this service. // Metrics defines the available metrics of this service.
type Metrics struct { type Metrics struct {
// Counter *prometheus.CounterVec // Counter *prometheus.CounterVec
BuildInfo *prometheus.GaugeVec
} }
// New initializes the available metrics. // New initializes the available metrics.
func New() *Metrics { func New() *Metrics {
m := &Metrics{ m := &Metrics{
// Counter: prometheus.NewCounterVec(prometheus.CounterOpts{ BuildInfo: prometheus.NewGaugeVec(prometheus.GaugeOpts{
// Namespace: Namespace, Namespace: Namespace,
// Subsystem: Subsystem, Subsystem: Subsystem,
// Name: "greet_total", Name: "build_info",
// Help: "How many greeting requests processed", Help: "Build information",
// }, []string{}), }, []string{"version"}),
} }
// prometheus.Register( _ = prometheus.Register(m.BuildInfo)
// m.Counter, // TODO: implement metrics
// )
return m return m
} }
+2 -1
View File
@@ -4,10 +4,11 @@ import (
"os" "os"
"github.com/owncloud/ocis/graph/pkg/command" "github.com/owncloud/ocis/graph/pkg/command"
"github.com/owncloud/ocis/graph/pkg/config"
) )
func main() { func main() {
if err := command.Execute(); err != nil { if err := command.Execute(config.New()); err != nil {
os.Exit(1) os.Exit(1)
} }
} }
+30 -4
View File
@@ -1,25 +1,26 @@
package command package command
import ( import (
"context"
"os" "os"
"strings" "strings"
"github.com/owncloud/ocis/ocis-pkg/sync" "github.com/owncloud/ocis/ocis-pkg/sync"
"github.com/thejerf/suture/v4"
"github.com/micro/cli/v2" "github.com/micro/cli/v2"
"github.com/owncloud/ocis/graph/pkg/config" "github.com/owncloud/ocis/graph/pkg/config"
"github.com/owncloud/ocis/graph/pkg/flagset" "github.com/owncloud/ocis/graph/pkg/flagset"
"github.com/owncloud/ocis/graph/pkg/version" "github.com/owncloud/ocis/graph/pkg/version"
ociscfg "github.com/owncloud/ocis/ocis-pkg/config"
"github.com/owncloud/ocis/ocis-pkg/log" "github.com/owncloud/ocis/ocis-pkg/log"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
// Execute is the entry point for the ocis-graph command. // Execute is the entry point for the ocis-graph command.
func Execute() error { func Execute(cfg *config.Config) error {
cfg := config.New()
app := &cli.App{ app := &cli.App{
Name: "graph", Name: "ocis-graph",
Version: version.String, Version: version.String,
Usage: "Serve Graph API for oCIS", Usage: "Serve Graph API for oCIS",
Compiled: version.Compiled(), Compiled: version.Compiled(),
@@ -34,6 +35,7 @@ func Execute() error {
Flags: flagset.RootWithConfig(cfg), Flags: flagset.RootWithConfig(cfg),
Before: func(c *cli.Context) error { Before: func(c *cli.Context) error {
cfg.Server.Version = version.String
return ParseConfig(c, cfg) return ParseConfig(c, cfg)
}, },
@@ -110,3 +112,27 @@ func ParseConfig(c *cli.Context, cfg *config.Config) error {
return nil return nil
} }
// SutureService allows for the graph command to be embedded and supervised by a suture supervisor tree.
type SutureService struct {
cfg *config.Config
}
// NewSutureService creates a new graph.SutureService
func NewSutureService(cfg *ociscfg.Config) suture.Service {
if cfg.Mode == 0 {
cfg.Graph.Supervised = true
}
return SutureService{
cfg: cfg.Graph,
}
}
func (s SutureService) Serve(ctx context.Context) error {
s.cfg.Context = ctx
if err := Execute(s.cfg); err != nil {
return err
}
return nil
}
+27 -50
View File
@@ -2,8 +2,6 @@ package command
import ( import (
"context" "context"
"os"
"os/signal"
"strings" "strings"
"time" "time"
@@ -19,6 +17,7 @@ import (
"github.com/owncloud/ocis/graph/pkg/metrics" "github.com/owncloud/ocis/graph/pkg/metrics"
"github.com/owncloud/ocis/graph/pkg/server/debug" "github.com/owncloud/ocis/graph/pkg/server/debug"
"github.com/owncloud/ocis/graph/pkg/server/http" "github.com/owncloud/ocis/graph/pkg/server/http"
"github.com/owncloud/ocis/ocis-pkg/sync"
"go.opencensus.io/stats/view" "go.opencensus.io/stats/view"
"go.opencensus.io/trace" "go.opencensus.io/trace"
) )
@@ -29,12 +28,19 @@ func Server(cfg *config.Config) *cli.Command {
Name: "server", Name: "server",
Usage: "Start integrated server", Usage: "Start integrated server",
Flags: flagset.ServerWithConfig(cfg), Flags: flagset.ServerWithConfig(cfg),
Before: func(c *cli.Context) error { Before: func(ctx *cli.Context) error {
logger := NewLogger(cfg)
if cfg.HTTP.Root != "/" { if cfg.HTTP.Root != "/" {
cfg.HTTP.Root = strings.TrimSuffix(cfg.HTTP.Root, "/") cfg.HTTP.Root = strings.TrimSuffix(cfg.HTTP.Root, "/")
} }
return ParseConfig(c, cfg) // When running on single binary mode the before hook from the root command won't get called. We manually
// call this before hook from ocis command, so the configuration can be loaded.
if !cfg.Supervised {
return ParseConfig(ctx, cfg)
}
logger.Debug().Str("service", "graph").Msg("ignoring config file parsing when running supervised")
return nil
}, },
Action: func(c *cli.Context) error { Action: func(c *cli.Context) error {
logger := NewLogger(cfg) logger := NewLogger(cfg)
@@ -125,28 +131,29 @@ func Server(cfg *config.Config) *cli.Command {
var ( var (
gr = run.Group{} gr = run.Group{}
ctx, cancel = context.WithCancel(context.Background()) ctx, cancel = func() (context.Context, context.CancelFunc) {
metrics = metrics.New() if cfg.Context == nil {
return context.WithCancel(context.Background())
}
return context.WithCancel(cfg.Context)
}()
mtrcs = metrics.New()
) )
defer cancel() defer cancel()
mtrcs.BuildInfo.WithLabelValues(cfg.Server.Version).Set(1)
{ {
server, err := http.Server( server, err := http.Server(
http.Logger(logger), http.Logger(logger),
http.Context(ctx), http.Context(ctx),
http.Config(cfg), http.Config(cfg),
http.Metrics(metrics), http.Metrics(mtrcs),
http.Flags(flagset.RootWithConfig(cfg)),
http.Flags(flagset.ServerWithConfig(cfg)),
) )
if err != nil { if err != nil {
logger.Info(). logger.Info().Err(err).Str("transport", "http").Msg("Failed to initialize server")
Err(err).
Str("transport", "http").
Msg("Failed to initialize server")
return err return err
} }
@@ -169,48 +176,18 @@ func Server(cfg *config.Config) *cli.Command {
) )
if err != nil { if err != nil {
logger.Info(). logger.Info().Err(err).Str("transport", "debug").Msg("Failed to initialize server")
Err(err).
Str("transport", "debug").
Msg("Failed to initialize server")
return err return err
} }
gr.Add(func() error { gr.Add(server.ListenAndServe, func(_ error) {
return server.ListenAndServe() _ = server.Shutdown(ctx)
}, func(_ error) { cancel()
ctx, timeout := context.WithTimeout(ctx, 5*time.Second)
defer timeout()
defer cancel()
if err := server.Shutdown(ctx); err != nil {
logger.Info().
Err(err).
Str("transport", "debug").
Msg("Failed to shutdown server")
} else {
logger.Info().
Str("transport", "debug").
Msg("Shutting down server")
}
}) })
} }
{ if !cfg.Supervised {
stop := make(chan os.Signal, 1) sync.Trap(&gr, cancel)
gr.Add(func() error {
signal.Notify(stop, os.Interrupt)
<-stop
return nil
}, func(err error) {
//close(stop)
cancel()
})
} }
return gr.Run() return gr.Run()
+12
View File
@@ -1,5 +1,7 @@
package config package config
import "context"
// Log defines the available logging configuration. // Log defines the available logging configuration.
type Log struct { type Log struct {
Level string Level string
@@ -22,6 +24,12 @@ type HTTP struct {
Root string Root string
} }
// Server configures a server.
type Server struct {
Version string
Name string
}
// Tracing defines the available tracing configuration. // Tracing defines the available tracing configuration.
type Tracing struct { type Tracing struct {
Enabled bool Enabled bool
@@ -60,10 +68,14 @@ type Config struct {
Log Log Log Log
Debug Debug Debug Debug
HTTP HTTP HTTP HTTP
Server Server
Tracing Tracing Tracing Tracing
Ldap Ldap Ldap Ldap
OpenIDConnect OpenIDConnect OpenIDConnect OpenIDConnect
Reva Reva Reva Reva
Context context.Context
Supervised bool
} }
// New initializes a new configuration with or without defaults. // New initializes a new configuration with or without defaults.
+3 -3
View File
@@ -122,7 +122,7 @@ func ServerWithConfig(cfg *config.Config) []cli.Flag {
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: "http-root", Name: "http-root",
Value: flags.OverrideDefaultString(cfg.HTTP.Root, "/"), Value: flags.OverrideDefaultString(cfg.HTTP.Root, "/graph"),
Usage: "Root path of http server", Usage: "Root path of http server",
EnvVars: []string{"GRAPH_HTTP_ROOT"}, EnvVars: []string{"GRAPH_HTTP_ROOT"},
Destination: &cfg.HTTP.Root, Destination: &cfg.HTTP.Root,
@@ -178,9 +178,9 @@ func ServerWithConfig(cfg *config.Config) []cli.Flag {
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: "oidc-endpoint", Name: "oidc-endpoint",
Value: flags.OverrideDefaultString(cfg.OpenIDConnect.Endpoint, "https://localhost:9130"), Value: flags.OverrideDefaultString(cfg.OpenIDConnect.Endpoint, "https://localhost:9200"),
Usage: "OpenIDConnect endpoint", Usage: "OpenIDConnect endpoint",
EnvVars: []string{"GRAPH_OIDC_ENDPOINT"}, EnvVars: []string{"GRAPH_OIDC_ENDPOINT", "OCIS_URL"},
Destination: &cfg.OpenIDConnect.Endpoint, Destination: &cfg.OpenIDConnect.Endpoint,
}, },
&cli.BoolFlag{ &cli.BoolFlag{
+11 -10
View File
@@ -1,5 +1,7 @@
package metrics package metrics
import "github.com/prometheus/client_golang/prometheus"
var ( var (
// Namespace defines the namespace for the defines metrics. // Namespace defines the namespace for the defines metrics.
Namespace = "ocis" Namespace = "ocis"
@@ -11,22 +13,21 @@ var (
// Metrics defines the available metrics of this service. // Metrics defines the available metrics of this service.
type Metrics struct { type Metrics struct {
// Counter *prometheus.CounterVec // Counter *prometheus.CounterVec
BuildInfo *prometheus.GaugeVec
} }
// New initializes the available metrics. // New initializes the available metrics.
func New() *Metrics { func New() *Metrics {
m := &Metrics{ m := &Metrics{
// Counter: prometheus.NewCounterVec(prometheus.CounterOpts{ BuildInfo: prometheus.NewGaugeVec(prometheus.GaugeOpts{
// Namespace: Namespace, Namespace: Namespace,
// Subsystem: Subsystem, Subsystem: Subsystem,
// Name: "greet_total", Name: "build_info",
// Help: "How many greeting requests processed", Help: "Build information",
// }, []string{}), }, []string{"version"}),
} }
// prometheus.Register( _ = prometheus.Register(m.BuildInfo)
// m.Counter, // TODO: implement metrics
// )
return m return m
} }
+5 -3
View File
@@ -23,7 +23,8 @@ func (g Graph) GroupCtx(next http.Handler) http.Handler {
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest) errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest)
return return
} }
filter := fmt.Sprintf("(entryuuid=%s)", groupID) // TODO make filter configurable
filter := fmt.Sprintf("(&(objectClass=posixGroup)(ownCloudUUID=%s))", groupID)
group, err := g.ldapGetSingleEntry(g.config.Ldap.BaseDNGroups, filter) group, err := g.ldapGetSingleEntry(g.config.Ldap.BaseDNGroups, filter)
if err != nil { if err != nil {
g.logger.Info().Err(err).Msgf("Failed to read group %s", groupID) g.logger.Info().Err(err).Msgf("Failed to read group %s", groupID)
@@ -45,10 +46,11 @@ func (g Graph) GetGroups(w http.ResponseWriter, r *http.Request) {
return return
} }
result, err := g.ldapSearch(con, "(objectclass=*)", g.config.Ldap.BaseDNGroups) // TODO make filter configurable
result, err := g.ldapSearch(con, "(objectClass=posixGroup)", g.config.Ldap.BaseDNGroups)
if err != nil { if err != nil {
g.logger.Error().Err(err).Msg("Failed search ldap with filter: '(objectclass=*)'") g.logger.Error().Err(err).Msg("Failed search ldap with filter: '(objectClass=posixGroup)'")
errorcode.ServiceNotAvailable.Render(w, r, http.StatusInternalServerError) errorcode.ServiceNotAvailable.Render(w, r, http.StatusInternalServerError)
return return
} }
+7 -4
View File
@@ -27,7 +27,8 @@ func (g Graph) UserCtx(next http.Handler) http.Handler {
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest) errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest)
return return
} }
filter := fmt.Sprintf("(entryuuid=%s)", userID) // TODO make filter configurable
filter := fmt.Sprintf("(&(objectClass=posixAccount)(ownCloudUUID=%s))", userID)
user, err = g.ldapGetSingleEntry(g.config.Ldap.BaseDNUsers, filter) user, err = g.ldapGetSingleEntry(g.config.Ldap.BaseDNUsers, filter)
if err != nil { if err != nil {
g.logger.Info().Err(err).Msgf("Failed to read user %s", userID) g.logger.Info().Err(err).Msgf("Failed to read user %s", userID)
@@ -45,7 +46,8 @@ func (g Graph) GetMe(w http.ResponseWriter, r *http.Request) {
claims := oidc.FromContext(r.Context()) claims := oidc.FromContext(r.Context())
g.logger.Info().Interface("Claims", claims).Msg("Claims in /me") g.logger.Info().Interface("Claims", claims).Msg("Claims in /me")
filter := fmt.Sprintf("(uid=%s)", claims.PreferredUsername) // TODO make filter configurable
filter := fmt.Sprintf("(&(objectClass=posixAccount)(cn=%s))", claims.PreferredUsername)
user, err := g.ldapGetSingleEntry(g.config.Ldap.BaseDNUsers, filter) user, err := g.ldapGetSingleEntry(g.config.Ldap.BaseDNUsers, filter)
if err != nil { if err != nil {
g.logger.Info().Err(err).Msgf("Failed to read user %s", claims.PreferredUsername) g.logger.Info().Err(err).Msgf("Failed to read user %s", claims.PreferredUsername)
@@ -68,10 +70,11 @@ func (g Graph) GetUsers(w http.ResponseWriter, r *http.Request) {
return return
} }
result, err := g.ldapSearch(con, "(objectclass=*)", g.config.Ldap.BaseDNUsers) // TODO make filter configurable
result, err := g.ldapSearch(con, "(objectClass=posixAccount)", g.config.Ldap.BaseDNUsers)
if err != nil { if err != nil {
g.logger.Error().Err(err).Msg("Failed search ldap with filter: '(objectclass=*)'") g.logger.Error().Err(err).Msg("Failed search ldap with filter: '(objectClass=posixAccount)'")
errorcode.ServiceNotAvailable.Render(w, r, http.StatusInternalServerError) errorcode.ServiceNotAvailable.Render(w, r, http.StatusInternalServerError)
return return
} }
+4
View File
@@ -19,6 +19,8 @@ import (
"github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter"
accounts "github.com/owncloud/ocis/accounts/pkg/command" accounts "github.com/owncloud/ocis/accounts/pkg/command"
glauth "github.com/owncloud/ocis/glauth/pkg/command" glauth "github.com/owncloud/ocis/glauth/pkg/command"
graph "github.com/owncloud/ocis/graph/pkg/command"
graphExplorer "github.com/owncloud/ocis/graph-explorer/pkg/command"
idp "github.com/owncloud/ocis/idp/pkg/command" idp "github.com/owncloud/ocis/idp/pkg/command"
ociscfg "github.com/owncloud/ocis/ocis-pkg/config" ociscfg "github.com/owncloud/ocis/ocis-pkg/config"
"github.com/owncloud/ocis/ocis-pkg/log" "github.com/owncloud/ocis/ocis-pkg/log"
@@ -82,6 +84,8 @@ func NewService(options ...Option) (*Service, error) {
s.ServicesRegistry["settings"] = settings.NewSutureService s.ServicesRegistry["settings"] = settings.NewSutureService
s.ServicesRegistry["storage-metadata"] = storage.NewStorageMetadata s.ServicesRegistry["storage-metadata"] = storage.NewStorageMetadata
s.ServicesRegistry["glauth"] = glauth.NewSutureService s.ServicesRegistry["glauth"] = glauth.NewSutureService
s.ServicesRegistry["graph"] = graph.NewSutureService
s.ServicesRegistry["graph-explorer"] = graphExplorer.NewSutureService
s.ServicesRegistry["idp"] = idp.NewSutureService s.ServicesRegistry["idp"] = idp.NewSutureService
s.ServicesRegistry["ocs"] = ocs.NewSutureService s.ServicesRegistry["ocs"] = ocs.NewSutureService
s.ServicesRegistry["onlyoffice"] = onlyoffice.NewSutureService s.ServicesRegistry["onlyoffice"] = onlyoffice.NewSutureService
+8
View File
@@ -322,6 +322,14 @@ func defaultPolicies() []config.Policy {
Endpoint: "/data", Endpoint: "/data",
Backend: "http://localhost:9140", Backend: "http://localhost:9140",
}, },
{
Endpoint: "/graph/",
Backend: "http://localhost:9120",
},
{
Endpoint: "/graph-explorer/",
Backend: "http://localhost:9135",
},
// if we were using the go micro api gateway we could look up the endpoint in the registry dynamically // if we were using the go micro api gateway we could look up the endpoint in the registry dynamically
{ {
Endpoint: "/api/v0/accounts", Endpoint: "/api/v0/accounts",
+1 -1
View File
@@ -35,7 +35,7 @@ func HealthWithConfig(cfg *config.Config) []cli.Flag {
return []cli.Flag{ return []cli.Flag{
&cli.StringFlag{ &cli.StringFlag{
Name: "debug-addr", Name: "debug-addr",
Value: "0.0.0.0:9104", Value: flags.OverrideDefaultString(cfg.Debug.Addr, "0.0.0.0:9104"),
Usage: "Address to debug endpoint", Usage: "Address to debug endpoint",
EnvVars: []string{"WEB_DEBUG_ADDR"}, EnvVars: []string{"WEB_DEBUG_ADDR"},
Destination: &cfg.Debug.Addr, Destination: &cfg.Debug.Addr,