defaultinit

package
v0.59.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 17, 2026 License: Apache-2.0 Imports: 42 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// InitializerIDParameterStores registers parameter stores.
	InitializerIDParameterStores coreinit.InitializerID = "khi.default/parameter-stores"

	// InitializerIDParameterParse parses parameters and injects them into InitContext.
	InitializerIDParameterParse coreinit.InitializerID = "khi.default/parameter-parse"
)
View Source
const InitializerIDCELValidationService coreinit.InitializerID = "khi.default/cel-validation-service"

InitializerIDCELValidationService identifies the Initializer that mounts the CELValidationService.

View Source
const InitializerIDDebugFeatures coreinit.InitializerID = "khi.default/debug-features"

InitializerIDDebugFeatures configures profiler and Cloud Trace.

View Source
const InitializerIDFileParameterUpload coreinit.InitializerID = "khi.default/file-parameter-upload"

InitializerIDFileParameterUpload mounts Connect-RPC FileParameterUploadService onto Gin engine.

View Source
const InitializerIDGinEngine coreinit.InitializerID = "khi.default/gin-engine"

InitializerIDGinEngine creates the Gin engine and attaches global middlewares.

View Source
const InitializerIDGinServer coreinit.InitializerID = "khi.default/gin-server"

InitializerIDGinServer mounts default REST endpoints and static files onto Gin engine.

View Source
const InitializerIDImportInspection coreinit.InitializerID = "khi.default/import-inspection"

InitializerIDImportInspection mounts Connect-RPC ImportInspectionService onto Gin engine.

View Source
const InitializerIDInspectionIndexManager coreinit.InitializerID = "khi.default/inspection-index-manager"

InitializerIDInspectionIndexManager identifies the Initializer that creates the InspectionIndexManager.

View Source
const InitializerIDInspectionService coreinit.InitializerID = "khi.default/inspection-service"

InitializerIDInspectionService mounts Connect-RPC InspectionService onto Gin engine.

View Source
const InitializerIDInspectionTaskGraph coreinit.InitializerID = "khi.default/inspection-task-graph"

InitializerIDInspectionTaskGraph mounts Connect-RPC InspectionTaskGraphService onto Gin engine.

View Source
const InitializerIDInspectionTaskServer coreinit.InitializerID = "khi.default/inspection-task-server"

InitializerIDInspectionTaskServer creates InspectionTaskServer and registers tasks.

View Source
const InitializerIDJobRunner coreinit.InitializerID = "khi.default/job-runner"

InitializerIDJobRunner executes batch inspection tasks in job mode.

View Source
const InitializerIDK8sMergeConfig coreinit.InitializerID = "khi.default/k8s-merge-config"

InitializerIDK8sMergeConfig generates default merge configs.

View Source
const InitializerIDLogger coreinit.InitializerID = "khi.default/logger"

InitializerIDLogger initializes the global logger.

View Source
const InitializerIDOAuth coreinit.InitializerID = "khi.default/oauth"

InitializerIDOAuth initializes OAuth authentication handlers if enabled.

View Source
const InitializerIDPopupService coreinit.InitializerID = "khi.default/popup-service"

InitializerIDPopupService identifies the Initializer that mounts the PopupService.

View Source
const InitializerIDServerRunner coreinit.InitializerID = "khi.default/server-runner"

InitializerIDServerRunner starts the HTTP server listener and prints the banner.

View Source
const InitializerIDServerStatusService coreinit.InitializerID = "khi.default/server-status-service"

InitializerIDServerStatusService identifies the Initializer that mounts the ServerStatusService.

View Source
const InitializerIDWorkbenchService coreinit.InitializerID = "khi.default/workbench-service"

InitializerIDWorkbenchService identifies the Initializer that mounts the WorkbenchService.

Variables

View Source
var (
	// IOConfigKey stores the IOConfig instance.
	IOConfigKey = typedmap.NewTypedKey[*inspectioncore.IOConfig]("khi.google.com/init/io-config")

	// InspectionTaskServerKey stores the InspectionTaskServer instance.
	InspectionTaskServerKey = typedmap.NewTypedKey[*coreinspection.InspectionTaskServer]("khi.google.com/init/inspection-task-server")
)
View Source
var (
	// CommonParametersKey stores parsed CommonParameters.
	CommonParametersKey = typedmap.NewTypedKey[*parameters.CommonParameters]("khi.google.com/init/params/common")

	// ServerParametersKey stores parsed ServerParameters.
	ServerParametersKey = typedmap.NewTypedKey[*parameters.ServerParameters]("khi.google.com/init/params/server")

	// JobParametersKey stores parsed JobParameters.
	JobParametersKey = typedmap.NewTypedKey[*parameters.JobParameters]("khi.google.com/init/params/job")

	// AuthParametersKey stores parsed AuthParameters.
	AuthParametersKey = typedmap.NewTypedKey[*parameters.AuthParameters]("khi.google.com/init/params/auth")

	// DebugParametersKey stores parsed DebugParameters.
	DebugParametersKey = typedmap.NewTypedKey[*parameters.DebugParameters]("khi.google.com/init/params/debug")

	// RateLimitParametersKey stores parsed RateLimitParameters.
	RateLimitParametersKey = typedmap.NewTypedKey[*parameters.RateLimitParameters]("khi.google.com/init/params/ratelimit")
)
View Source
var (
	// UploadStoreKey stores the UploadFileStore instance.
	UploadStoreKey = typedmap.NewTypedKey[*upload.UploadFileStore]("khi.google.com/init/upload-store")

	// GinRouterKey stores the base gin.IRouter instance.
	GinRouterKey = typedmap.NewTypedKey[gin.IRouter]("khi.google.com/init/gin-router")

	// BasePathKey stores the normalized server base path.
	BasePathKey = typedmap.NewTypedKey[string]("khi.google.com/init/base-path")
)
View Source
var (
	// WorkbenchManagerKey stores the WorkbenchManager instance in the init context.
	WorkbenchManagerKey = typedmap.NewTypedKey[*workbench.WorkbenchManager]("khi.google.com/init/workbench-manager")
	// InspectionIndexManagerKey stores the InspectionIndexManager instance in the init context.
	InspectionIndexManagerKey = typedmap.NewTypedKey[*workbench.InspectionIndexManager]("khi.google.com/init/inspection-index-manager")
)
View Source
var CELValidationServiceInitializer = &coreinit.Initializer{
	ID: InitializerIDCELValidationService,
	Dependencies: []coreinit.InitializerID{
		InitializerIDGinServer,
	},
	Before: []coreinit.InitializerID{
		InitializerIDServerRunner,
	},
	Init: func(ctx *coreinit.InitContext) error {
		jobParams := coreinit.MustGet(ctx, JobParametersKey)
		if *jobParams.JobMode {
			return nil
		}
		router := coreinit.MustGet(ctx, GinRouterKey)
		basePath := coreinit.MustGet(ctx, BasePathKey)

		celValidationPath, celValidationHandler := apiv1connect.NewCELValidationServiceHandler(apiv1impl.NewCELValidationServer())
		coreinit.RegisterConnectServiceHandler(router, basePath, celValidationPath, celValidationHandler)
		return nil
	},
}

CELValidationServiceInitializer mounts the CELValidationService Connect-RPC handler onto the Gin router.

View Source
var DebugFeaturesInitializer = &coreinit.Initializer{
	ID: InitializerIDDebugFeatures,
	Dependencies: []coreinit.InitializerID{
		InitializerIDParameterParse,
	},
	Init: func(ctx *coreinit.InitContext) error {
		debugParams := coreinit.MustGet(ctx, DebugParametersKey)
		if *debugParams.Verbose {
			flag.DumpAll(ctx)
		}
		if *debugParams.Profiler {
			cfg := profiler.Config{
				Service:        *debugParams.ProfilerService,
				ProjectID:      *debugParams.ProfilerProject,
				MutexProfiling: true,
			}
			if err := profiler.Start(cfg); err != nil {
				return err
			}
			slog.Info("Cloud Profiler is enabled")
		}
		if *debugParams.CloudTrace {
			exporter, err := texporter.New(texporter.WithProjectID(*debugParams.CloudTraceProject))
			if err != nil {
				return err
			}
			tp := sdktrace.NewTracerProvider(
				sdktrace.WithBatcher(exporter),
				sdktrace.WithResource(resource.NewWithAttributes(
					semconv.SchemaURL,
					semconv.ServiceNameKey.String("khi"),
					semconv.ServiceVersionKey.String(constants.VERSION),
				)),
			)
			otel.SetTracerProvider(tp)
			slog.Info("Cloud Trace is enabled")
		}
		if *debugParams.CPUProfile != "" {
			f, err := os.Create(*debugParams.CPUProfile)
			if err != nil {
				return err
			}
			if err := pprof.StartCPUProfile(f); err != nil {
				f.Close()
				return err
			}
			slog.Info("CPU profiling is enabled", "file", *debugParams.CPUProfile)
			ctx.OnTerminate(func() error {
				pprof.StopCPUProfile()
				return f.Close()
			})
		}
		if *debugParams.MemProfile != "" {
			memProfilePath := *debugParams.MemProfile
			slog.Info("Memory profiling is enabled", "file", memProfilePath)
			ctx.OnTerminate(func() error {
				f, err := os.Create(memProfilePath)
				if err != nil {
					return err
				}
				defer f.Close()
				runtime.GC()
				if err := pprof.WriteHeapProfile(f); err != nil {
					return err
				}
				slog.Info("Memory profile written", "file", memProfilePath)
				return nil
			})
		}
		return nil
	},
}

DebugFeaturesInitializer initializes optional debug tooling (Profiler and Cloud Trace).

View Source
var FileParameterUploadInitializer = &coreinit.Initializer{
	ID: InitializerIDFileParameterUpload,
	Dependencies: []coreinit.InitializerID{
		InitializerIDGinServer,
	},
	Before: []coreinit.InitializerID{
		InitializerIDServerRunner,
	},
	Init: func(ctx *coreinit.InitContext) error {
		jobParams := coreinit.MustGet(ctx, JobParametersKey)
		if *jobParams.JobMode {
			return nil
		}

		uploadStore := coreinit.MustGet(ctx, UploadStoreKey)
		router := coreinit.MustGet(ctx, GinRouterKey)
		basePath := coreinit.MustGet(ctx, BasePathKey)
		commonParams := coreinit.MustGet(ctx, CommonParametersKey)

		uploadFolder := "/tmp"
		if commonParams.UploadFileStoreFolder != nil {
			uploadFolder = *commonParams.UploadFileStoreFolder
		}

		chunkManager := chunkedupload.NewChunkSessionManager(uploadFolder)
		manager := upload.NewFileParameterUploadManager(uploadStore, chunkManager)
		fileUploadServer := serverapiv1.NewFileParameterUploadServiceServer(manager)
		fileUploadPath, fileUploadHandler := apiv1connect.NewFileParameterUploadServiceHandler(fileUploadServer)
		coreinit.RegisterConnectServiceHandler(router, basePath, fileUploadPath, fileUploadHandler)

		return nil
	},
}

FileParameterUploadInitializer initializes and registers the FileParameterUploadService handlers.

View Source
var GinEngineInitializer = &coreinit.Initializer{
	ID: InitializerIDGinEngine,
	Dependencies: []coreinit.InitializerID{
		InitializerIDParameterParse,
	},
	Before: []coreinit.InitializerID{
		InitializerIDGinServer,
	},
	Init: func(ctx *coreinit.InitContext) error {
		jobParams := coreinit.MustGet(ctx, JobParametersKey)
		if *jobParams.JobMode {
			return nil
		}
		debugParams := coreinit.MustGet(ctx, DebugParametersKey)

		serverMode := gin.ReleaseMode
		if *debugParams.Verbose {
			serverMode = gin.DebugMode
		}
		gin.SetMode(serverMode)

		engine := gin.New()
		engine.Use(gin.Recovery())
		if *debugParams.Verbose {
			engine.Use(gin.LoggerWithConfig(gin.LoggerConfig{
				SkipPaths: []string{"/api/v3/inspection", "/api/v3/popup"},
			}))
		}

		coreinit.Set(ctx, GinEngineKey, engine)
		return nil
	},
}

GinEngineInitializer creates the gin.Engine instance and sets up base global middlewares.

View Source
var (
	// GinEngineKey stores the gin.Engine instance.
	GinEngineKey = typedmap.NewTypedKey[*gin.Engine]("khi.google.com/init/gin-engine")
)
View Source
var GinServerInitializer = &coreinit.Initializer{
	ID: InitializerIDGinServer,
	Dependencies: []coreinit.InitializerID{
		InitializerIDGinEngine,
	},
	Before: []coreinit.InitializerID{
		InitializerIDServerRunner,
	},
	Init: func(ctx *coreinit.InitContext) error {
		jobParams := coreinit.MustGet(ctx, JobParametersKey)
		if *jobParams.JobMode {
			return nil
		}
		commonParams := coreinit.MustGet(ctx, CommonParametersKey)
		serverParams := coreinit.MustGet(ctx, ServerParametersKey)

		uploadFileStoreFolder := "/tmp"
		if commonParams.UploadFileStoreFolder != nil {
			uploadFileStoreFolder = *commonParams.UploadFileStoreFolder
		}
		uploadFileStore := upload.NewUploadFileStore(upload.NewLocalUploadFileStoreProvider(uploadFileStoreFolder))
		upload.DefaultUploadFileStore = uploadFileStore
		coreinit.Set(ctx, UploadStoreKey, uploadFileStore)

		engine := coreinit.MustGet(ctx, GinEngineKey)
		basePath := strings.TrimSuffix(*serverParams.BasePath, "/")
		var router gin.IRouter = engine.Group(basePath)

		coreinit.Set(ctx, GinRouterKey, router)
		coreinit.Set(ctx, BasePathKey, basePath)

		server.SetupFrontendMiddleware(engine, basePath, *serverParams.FrontendAssetFolder)
		server.SetupFrontendRoutes(router, *serverParams.FrontendAssetFolder)
		return nil
	},
}

GinServerInitializer mounts standard KHI HTTP routes, frontend assets, and store configs onto gin.Engine.

View Source
var ImportInspectionInitializer = &coreinit.Initializer{
	ID: InitializerIDImportInspection,
	Dependencies: []coreinit.InitializerID{
		InitializerIDGinServer,
		InitializerIDInspectionTaskServer,
		InitializerIDInspectionIndexManager,
	},
	Before: []coreinit.InitializerID{
		InitializerIDServerRunner,
	},
	Init: func(ctx *coreinit.InitContext) error {
		jobParams := coreinit.MustGet(ctx, JobParametersKey)
		if *jobParams.JobMode {
			return nil
		}

		inspectionServer := coreinit.MustGet(ctx, InspectionTaskServerKey)
		indexManager := coreinit.MustGet(ctx, InspectionIndexManagerKey)
		router := coreinit.MustGet(ctx, GinRouterKey)
		basePath := coreinit.MustGet(ctx, BasePathKey)

		importSessionManager := importinspection.NewImportSessionManager(inspectionServer, inspectionServer.IOConfig())
		importInspectionServer := serverapiv1.NewImportInspectionServiceServer(importSessionManager, indexManager)
		importInspectionPath, importInspectionHandler := apiv1connect.NewImportInspectionServiceHandler(importInspectionServer)
		coreinit.RegisterConnectServiceHandler(router, basePath, importInspectionPath, importInspectionHandler)

		return nil
	},
}

ImportInspectionInitializer initializes and registers the ImportInspectionService handlers.

View Source
var InspectionIndexManagerInitializer = &coreinit.Initializer{
	ID: InitializerIDInspectionIndexManager,
	Dependencies: []coreinit.InitializerID{
		InitializerIDInspectionTaskServer,
	},
	Init: func(ctx *coreinit.InitContext) error {
		inspectionServer := coreinit.MustGet(ctx, InspectionTaskServerKey)
		dataDir := inspectionServer.IOConfig().DataDestination
		indexManager := workbench.NewInspectionIndexManager(inspectionServer, dataDir)
		coreinit.Set(ctx, InspectionIndexManagerKey, indexManager)
		return nil
	},
}

InspectionIndexManagerInitializer initializes the persistent InspectionIndexManager.

View Source
var InspectionServiceInitializer = &coreinit.Initializer{
	ID: InitializerIDInspectionService,
	Dependencies: []coreinit.InitializerID{
		InitializerIDGinServer,
		InitializerIDInspectionTaskServer,
	},
	Before: []coreinit.InitializerID{
		InitializerIDServerRunner,
	},
	Init: func(ctx *coreinit.InitContext) error {
		jobParams := coreinit.MustGet(ctx, JobParametersKey)
		if *jobParams.JobMode {
			return nil
		}

		inspectionServer := coreinit.MustGet(ctx, InspectionTaskServerKey)
		router := coreinit.MustGet(ctx, GinRouterKey)
		basePath := coreinit.MustGet(ctx, BasePathKey)

		inspectionServiceServer := serverapiv1.NewInspectionServiceServer(inspectionServer)
		inspectionServicePath, inspectionServiceHandler := apiv1connect.NewInspectionServiceHandler(inspectionServiceServer)
		coreinit.RegisterConnectServiceHandler(router, basePath, inspectionServicePath, inspectionServiceHandler)

		return nil
	},
}

InspectionServiceInitializer initializes and registers the InspectionService handlers.

View Source
var InspectionTaskGraphInitializer = &coreinit.Initializer{
	ID: InitializerIDInspectionTaskGraph,
	Dependencies: []coreinit.InitializerID{
		InitializerIDGinServer,
		InitializerIDInspectionTaskServer,
	},
	Before: []coreinit.InitializerID{
		InitializerIDServerRunner,
	},
	Init: func(ctx *coreinit.InitContext) error {
		jobParams := coreinit.MustGet(ctx, JobParametersKey)
		if *jobParams.JobMode {
			return nil
		}

		inspectionServer := coreinit.MustGet(ctx, InspectionTaskServerKey)
		router := coreinit.MustGet(ctx, GinRouterKey)
		basePath := coreinit.MustGet(ctx, BasePathKey)

		inspectionTaskGraphServer := serverapiv1.NewInspectionTaskGraphServer(
			inspectionServer,
			serverapiv1.DefaultStreamCycleDuration,
			serverapiv1.DefaultUpdateInterval,
		)
		servicePath, serviceHandler := apiv1connect.NewInspectionTaskGraphServiceHandler(inspectionTaskGraphServer)
		coreinit.RegisterConnectServiceHandler(router, basePath, servicePath, serviceHandler)

		return nil
	},
}

InspectionTaskGraphInitializer initializes and registers the InspectionTaskGraphService handlers.

View Source
var InspectionTaskServerInitializer = &coreinit.Initializer{
	ID: InitializerIDInspectionTaskServer,
	Dependencies: []coreinit.InitializerID{
		InitializerIDParameterParse,
		InitializerIDDebugFeatures,
		InitializerIDK8sMergeConfig,
	},
	Init: func(ctx *coreinit.InitContext) error {
		commonParams := coreinit.MustGet(ctx, CommonParametersKey)
		authParams := coreinit.MustGet(ctx, AuthParametersKey)
		debugParams := coreinit.MustGet(ctx, DebugParametersKey)

		ioconfig, err := inspectioncore.NewIOConfigFromParameter(commonParams)
		if err != nil {
			return fmt.Errorf("failed to construct IOConfig: %w", err)
		}
		inspectionServer, err := coreinspection.NewServer(ioconfig)
		if err != nil {
			return fmt.Errorf("failed to construct inspection server: %w", err)
		}

		if err := generated.RegisterAllInspectionTasks(inspectionServer); err != nil {
			return err
		}
		style.LockRegistry()
		inspectionServer.AddRunContextOption(coreinspection.RunContextOptionArrayElementFromValue(
			gcpcommon.APIClientFactoryOptionsContextKey,
			options.GRPCConnPool(*authParams.GRPCConnPool),
		))
		if *authParams.QuotaProjectID != "" {
			inspectionServer.AddRunContextOption(coreinspection.RunContextOptionArrayElementFromValue(
				gcpcommon.APIClientFactoryOptionsContextKey,
				options.QuotaProject(*authParams.QuotaProjectID),
			))
		}
		if *authParams.AccessToken != "" {
			inspectionServer.AddRunContextOption(coreinspection.RunContextOptionArrayElementFromValue(
				gcpcommon.APIClientFactoryOptionsContextKey,
				options.TokenSource(legacy.NewRawTokenTokenSource(*authParams.AccessToken)),
			))
		}
		if *debugParams.CloudTrace {
			inspectionServer.AddInspectionInterceptor(tracing.NewInspectionTraceInterceptor(otel.Tracer("khi")))
		}

		coreinit.Set(ctx, IOConfigKey, ioconfig)
		coreinit.Set(ctx, InspectionTaskServerKey, inspectionServer)
		return nil
	},
}

InspectionTaskServerInitializer constructs the inspection task server and registers all tasks.

View Source
var JobRunnerInitializer = &coreinit.Initializer{
	ID: InitializerIDJobRunner,
	Dependencies: []coreinit.InitializerID{
		InitializerIDInspectionTaskServer,
		InitializerIDParameterParse,
	},
	Init: func(ctx *coreinit.InitContext) error {
		jobParams := coreinit.MustGet(ctx, JobParametersKey)
		if !*jobParams.JobMode {
			return nil
		}
		upload.DefaultUploadFileStore = upload.NewJobModeStore()
		inspectionServer := coreinit.MustGet(ctx, InspectionTaskServerKey)

		ctx.OnRun(func(runCtx context.Context) error {
			slog.Info("Starting Kubernetes History Inspector as job mode...")
			queryParametersInJson := *jobParams.InspectionValues
			var values map[string]any
			if err := json.Unmarshal([]byte(queryParametersInJson), &values); err != nil {
				return fmt.Errorf("failed to parse inspection value %s: %w", queryParametersInJson, err)
			}
			inspectionID, err := inspectionServer.CreateInspection(*jobParams.InspectionType)
			if err != nil {
				return fmt.Errorf("failed to create inspection type %s: %w", *jobParams.InspectionType, err)
			}

			features := strings.Split(*jobParams.InspectionFeatures, ",")
			t := inspectionServer.GetInspection(inspectionID)
			if len(features) == 1 && strings.ToUpper(features[0]) == "ALL" {
				availableFeatures, err := t.FeatureList()
				if err != nil {
					return fmt.Errorf("failed to obtain feature list: %w", err)
				}
				allFeatures := []string{}
				for _, af := range availableFeatures {
					allFeatures = append(allFeatures, af.Id)
				}
				features = allFeatures
			}
			if err := t.SetFeatureList(features); err != nil {
				return fmt.Errorf("failed to set features: %w", err)
			}
			if err := t.Run(runCtx, &inspectioncore.InspectionRequest{Values: values}); err != nil {
				return fmt.Errorf("failed to run inspection task: %w", err)
			}
			<-t.Wait()
			result, err := t.Result()
			if err != nil {
				return fmt.Errorf("failed to get inspection result: %w", err)
			}
			reader, err := result.ResultStore.GetReader()
			if err != nil {
				return fmt.Errorf("failed to get result reader: %w", err)
			}
			defer reader.Close()
			file, err := os.OpenFile(*jobParams.ExportDestination, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
			if err != nil {
				return fmt.Errorf("failed to open export file: %w", err)
			}
			defer file.Close()
			if _, err := io.Copy(file, reader); err != nil {
				return fmt.Errorf("failed to write export file: %w", err)
			}
			if err := file.Sync(); err != nil {
				return fmt.Errorf("failed to sync export file: %w", err)
			}
			return nil
		})
		return nil
	},
}

JobRunnerInitializer handles batch execution when JobMode is enabled.

K8sMergeConfigInitializer initializes the default Kubernetes merge configurations.

View Source
var LoggerInitializer = &coreinit.Initializer{
	ID: InitializerIDLogger,
	Init: func(ctx *coreinit.InitContext) error {
		logger.InitGlobalKHILogger()
		slog.Info("Initializing Kubernetes History Inspector...")
		return nil
	},
}

LoggerInitializer initializes the global KHI logger.

View Source
var OAuthInitializer = &coreinit.Initializer{
	ID: InitializerIDOAuth,
	Dependencies: []coreinit.InitializerID{
		InitializerIDGinServer,
		InitializerIDInspectionTaskServer,
		InitializerIDParameterParse,
	},
	Before: []coreinit.InitializerID{
		InitializerIDServerRunner,
	},
	Init: func(ctx *coreinit.InitContext) error {
		authParams := coreinit.MustGet(ctx, AuthParametersKey)
		if !authParams.OAuthEnabled() {
			return nil
		}
		engine := coreinit.MustGet(ctx, GinEngineKey)
		taskServer := coreinit.MustGet(ctx, InspectionTaskServerKey)

		oauthServer := oauth.NewOAuthServer(engine, authParams.GetOAuthConfig(), *authParams.OAuthRedirectTargetServingPath, *authParams.OAuthStateSuffix)
		taskServer.AddRunContextOption(
			coreinspection.RunContextOptionArrayElementFromValue(gcpcommon.APIClientFactoryOptionsContextKey, options.OAuth(oauthServer)),
		)
		return nil
	},
}

OAuthInitializer sets up OAuth server endpoints and attaches credentials to the inspection task server.

ParameterParseInitializer parses CLI flags and injects parameter stores into InitContext.

ParameterStoresInitializer registers the standard KHI parameter stores.

View Source
var PopupServiceInitializer = &coreinit.Initializer{
	ID: InitializerIDPopupService,
	Dependencies: []coreinit.InitializerID{
		InitializerIDGinServer,
	},
	Before: []coreinit.InitializerID{
		InitializerIDServerRunner,
	},
	Init: func(ctx *coreinit.InitContext) error {
		jobParams := coreinit.MustGet(ctx, JobParametersKey)
		if *jobParams.JobMode {
			return nil
		}
		router := coreinit.MustGet(ctx, GinRouterKey)
		basePath := coreinit.MustGet(ctx, BasePathKey)

		popupPath, popupHandler := apiv1connect.NewPopupServiceHandler(apiv1impl.NewPopupServer(nil))
		coreinit.RegisterConnectServiceHandler(router, basePath, popupPath, popupHandler)
		return nil
	},
}

PopupServiceInitializer mounts the PopupService Connect-RPC handler onto the Gin router.

View Source
var ServerRunnerInitializer = &coreinit.Initializer{
	ID: InitializerIDServerRunner,
	Dependencies: []coreinit.InitializerID{
		InitializerIDGinServer,
	},
	Init: func(ctx *coreinit.InitContext) error {
		jobParams := coreinit.MustGet(ctx, JobParametersKey)
		if *jobParams.JobMode {
			return nil
		}
		serverParams := coreinit.MustGet(ctx, ServerParametersKey)
		debugParams := coreinit.MustGet(ctx, DebugParametersKey)
		engine := coreinit.MustGet(ctx, GinEngineKey)
		protocols := &http.Protocols{}
		protocols.SetHTTP1(true)
		protocols.SetUnencryptedHTTP2(true)

		srv := &http.Server{
			Addr:      fmt.Sprintf("%s:%d", *serverParams.Host, *serverParams.Port),
			Handler:   engine,
			Protocols: protocols,
		}

		ctx.OnRun(func(runCtx context.Context) error {
			slog.Info("Starting Kubernetes History Inspector server...")
			errCh := make(chan error, 1)
			go func() {
				if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
					slog.Error(fmt.Sprintf("Failed to start server: %v", err))
					errCh <- err
				}
			}()
			displayStartMessage(*serverParams.Host, *serverParams.Port, debugParams.NoColor != nil && *debugParams.NoColor)

			select {
			case <-runCtx.Done():
				return nil
			case err := <-errCh:
				return err
			}
		})

		ctx.OnTerminate(func() error {
			shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
			defer cancel()
			return srv.Shutdown(shutdownCtx)
		})

		return nil
	},
}

ServerRunnerInitializer registers the runtime server listener and graceful shutdown hooks.

View Source
var ServerStatusServiceInitializer = &coreinit.Initializer{
	ID: InitializerIDServerStatusService,
	Dependencies: []coreinit.InitializerID{
		InitializerIDGinServer,
	},
	Before: []coreinit.InitializerID{
		InitializerIDServerRunner,
	},
	Init: func(ctx *coreinit.InitContext) error {
		jobParams := coreinit.MustGet(ctx, JobParametersKey)
		if *jobParams.JobMode {
			return nil
		}
		router := coreinit.MustGet(ctx, GinRouterKey)
		basePath := coreinit.MustGet(ctx, BasePathKey)

		serverStatusPath, serverStatusHandler := apiv1connect.NewServerStatusServiceHandler(
			apiv1impl.NewServerStatusServiceServer(server.NewResourceMonitorImpl()),
		)
		coreinit.RegisterConnectServiceHandler(router, basePath, serverStatusPath, serverStatusHandler)
		return nil
	},
}

ServerStatusServiceInitializer mounts the ServerStatusService Connect-RPC handler onto the Gin router.

View Source
var WorkbenchServiceInitializer = &coreinit.Initializer{
	ID: InitializerIDWorkbenchService,
	Dependencies: []coreinit.InitializerID{
		InitializerIDGinServer,
		InitializerIDInspectionTaskServer,
		InitializerIDInspectionIndexManager,
	},
	Before: []coreinit.InitializerID{
		InitializerIDServerRunner,
	},
	Init: func(ctx *coreinit.InitContext) error {
		jobParams := coreinit.MustGet(ctx, JobParametersKey)
		if *jobParams.JobMode {
			return nil
		}
		inspectionServer := coreinit.MustGet(ctx, InspectionTaskServerKey)
		indexManager := coreinit.MustGet(ctx, InspectionIndexManagerKey)
		router := coreinit.MustGet(ctx, GinRouterKey)
		basePath := coreinit.MustGet(ctx, BasePathKey)

		workbenchManager := workbench.NewWorkbenchManager(inspectionServer, indexManager, 15*time.Minute, 15*time.Second)
		coreinit.Set(ctx, WorkbenchManagerKey, workbenchManager)

		workbenchPath, workbenchHandler := apiv1connect.NewWorkbenchServiceHandler(apiv1impl.NewWorkbenchServiceServer(workbenchManager))
		coreinit.RegisterConnectServiceHandler(router, basePath, workbenchPath, workbenchHandler)
		return nil
	},
}

WorkbenchServiceInitializer mounts the WorkbenchService Connect-RPC handler onto the Gin router.

Functions

func RegisterParameterStore added in v0.58.2

func RegisterParameterStore(id coreinit.InitializerID, store parameters.ParameterStore)

RegisterParameterStore registers a parameter store that will be added before parameters.Parse is executed.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL