googlecloudcommon_impl

package
v0.51.4 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

APICallOptionsInjectorTask is the default implementation to provide the CallOptionInjector. Each APIClient use must call this injector method before to supply parameters correctly.

APIClientFactoryOptionsTask is the default implementation to provide the list of googlecloud.ClientFactoryOption. User can extend this behavior with defining new task for googlecloudcommon_contract.APIClientFactoryOptionsTaskID with higher selection priority.

APIClientFactoryTask is a task to inject googlecloud.ClientFactory to the later tasks. The instance is singleton in an inspection and the instance is cached on inspection cache after the first generation.

View Source
var AutocompleteLocationTask = inspectiontaskbase.NewCachedTask(googlecloudcommon_contract.AutocompleteLocationTaskID,
	[]taskid.UntypedTaskReference{
		googlecloudcommon_contract.InputProjectIdTaskID.Ref(),
		googlecloudcommon_contract.LocationFetcherTaskID.Ref(),
	},
	func(ctx context.Context, prevValue inspectiontaskbase.CacheableTaskResult[[]string]) (inspectiontaskbase.CacheableTaskResult[[]string], error) {
		projectID := coretask.GetTaskResult(ctx, googlecloudcommon_contract.InputProjectIdTaskID.Ref())
		dependencyDigest := fmt.Sprintf("location-%s", projectID)

		if prevValue.DependencyDigest == dependencyDigest {
			return prevValue, nil
		}

		defaultResult := inspectiontaskbase.CacheableTaskResult[[]string]{
			DependencyDigest: dependencyDigest,
			Value:            []string{},
		}

		if projectID == "" {
			return defaultResult, nil
		}

		locationFetcher := coretask.GetTaskResult(ctx, googlecloudcommon_contract.LocationFetcherTaskID.Ref())
		regions, err := locationFetcher.FetchRegions(ctx, projectID)
		if err != nil {
			return defaultResult, nil
		}
		result := defaultResult
		result.Value = regions
		return result, nil
	})

AutocompleteLocationTask is a task that provides a list of available locations for autocomplete.

View Source
var InputDurationTask = formtask.NewTextFormTaskBuilder(googlecloudcommon_contract.InputDurationTaskID, googlecloudcommon_contract.PriorityForQueryTimeGroup+4000, "Duration").
	WithDependencies([]taskid.UntypedTaskReference{
		inspectioncore_contract.InspectionTimeTaskID.Ref(),
		googlecloudcommon_contract.InputEndTimeTaskID.Ref(),
		inspectioncore_contract.TimeZoneShiftInputTaskID.Ref(),
	}).
	WithDescription("The duration of time range to gather logs. Supported time units are `h`,`m` or `s`. (Example: `3h30m`)").
	WithDefaultValueFunc(func(ctx context.Context, previousValues []string) (string, error) {
		if len(previousValues) > 0 {
			return previousValues[0], nil
		} else {
			return "1h", nil
		}
	}).
	WithHintFunc(func(ctx context.Context, value string, convertedValue any) (string, inspectionmetadata.ParameterHintType, error) {
		inspectionTime := coretask.GetTaskResult(ctx, inspectioncore_contract.InspectionTimeTaskID.Ref())
		endTime := coretask.GetTaskResult(ctx, googlecloudcommon_contract.InputEndTimeTaskID.Ref())
		timezoneShift := coretask.GetTaskResult(ctx, inspectioncore_contract.TimeZoneShiftInputTaskID.Ref())

		duration := convertedValue.(time.Duration)
		startTime := endTime.Add(-duration)
		startToNow := inspectionTime.Sub(startTime)
		hintString := ""
		if startToNow > time.Hour*24*30 {
			hintString += "Specified time range starts from over than 30 days ago, maybe some logs are missing and the generated result could be incomplete.\n"
		}
		if duration > time.Hour*3 {
			hintString += "This duration can be too long for big clusters and lead OOM. Please retry with shorter duration when your machine crashed.\n"
		}
		hintString += fmt.Sprintf("Query range:\n%s\n", toTimeDurationWithTimezone(startTime, endTime, timezoneShift, true))
		hintString += fmt.Sprintf("(UTC: %s)\n", toTimeDurationWithTimezone(startTime, endTime, time.UTC, false))
		hintString += fmt.Sprintf("(PDT: %s)", toTimeDurationWithTimezone(startTime, endTime, time.FixedZone("PDT", -7*3600), false))
		return hintString, inspectionmetadata.Info, nil
	}).
	WithSuggestionsConstant([]string{"1m", "10m", "1h", "3h", "12h", "24h"}).
	WithValidator(func(ctx context.Context, value string) (string, error) {
		d, err := time.ParseDuration(value)
		if err != nil {
			return err.Error(), nil
		}
		if d <= 0 {
			return "duration must be positive", nil
		}
		return "", nil
	}).
	WithConverter(func(ctx context.Context, value string) (time.Duration, error) {
		d, err := time.ParseDuration(value)
		if err != nil {
			return 0, err
		}
		return d, nil
	}).
	Build()

InputDurationTask defines a form task to input the duration for log queries.

View Source
var InputEndTimeTask = formtask.NewTextFormTaskBuilder(googlecloudcommon_contract.InputEndTimeTaskID, googlecloudcommon_contract.PriorityForQueryTimeGroup+5000, "End time").
	WithDependencies([]taskid.UntypedTaskReference{
		inspectioncore_contract.TimeZoneShiftInputTaskID.Ref(),
	}).
	WithDescription(`The endtime of query. Please input it in the format of RFC3339
(example: 2006-01-02T15:04:05-07:00)`).
	WithSuggestionsFunc(func(ctx context.Context, value string, previousValues []string) ([]string, error) {
		return previousValues, nil
	}).
	WithDefaultValueFunc(func(ctx context.Context, previousValues []string) (string, error) {
		if len(previousValues) > 0 {
			return previousValues[0], nil
		}
		creationTime := khictx.MustGetValue(ctx, inspectioncore_contract.InspectionCreationTime)
		timezoneShift := coretask.GetTaskResult(ctx, inspectioncore_contract.TimeZoneShiftInputTaskID.Ref())

		return creationTime.In(timezoneShift).Format(time.RFC3339), nil
	}).
	WithHintFunc(func(ctx context.Context, value string, convertedValue any) (string, inspectionmetadata.ParameterHintType, error) {
		creationTime := khictx.MustGetValue(ctx, inspectioncore_contract.InspectionCreationTime)

		specifiedTime := convertedValue.(time.Time)
		if creationTime.Sub(specifiedTime) < 0 {
			return fmt.Sprintf("Specified time `%s` is pointing the future. Please make sure if you specified the right value", value), inspectionmetadata.Warning, nil
		}
		return "", inspectionmetadata.Info, nil
	}).
	WithValidator(func(ctx context.Context, value string) (string, error) {
		_, err := common.ParseTime(value)
		if err != nil {
			return "invalid time format. Please specify in the format of `2006-01-02T15:04:05-07:00`(RFC3339)", nil
		}
		return "", nil
	}).
	WithConverter(func(ctx context.Context, value string) (time.Time, error) {
		return common.ParseTime(value)
	}).
	Build()

InputEndTimeTask defines a form task to input the end time for log queries.

View Source
var InputLocationsTask = formtask.NewTextFormTaskBuilder(googlecloudcommon_contract.InputLocationsTaskID, googlecloudcommon_contract.PriorityForResourceIdentifierGroup+4500, "Location").
	WithDependencies([]taskid.UntypedTaskReference{googlecloudcommon_contract.AutocompleteLocationTaskID.Ref()}).
	WithDescription(
		"The location(region) to specify the resource exist(s|ed)",
	).
	WithDefaultValueFunc(func(ctx context.Context, previousValues []string) (string, error) {
		if len(previousValues) > 0 {
			return previousValues[0], nil
		}
		return "", nil
	}).
	WithSuggestionsFunc(func(ctx context.Context, value string, previousValues []string) ([]string, error) {
		if len(previousValues) > 0 {
			return previousValues, nil
		}
		regions := coretask.GetTaskResult(ctx, googlecloudcommon_contract.AutocompleteLocationTaskID.Ref())
		return common.SortForAutocomplete(value, regions), nil
	}).
	Build()

InputLocationsTask defines a form task for inputting the resource location.

View Source
var InputLoggingFilterResourceNameTask = inspectiontaskbase.NewInspectionTask(googlecloudcommon_contract.InputLoggingFilterResourceNameTaskID, []taskid.UntypedTaskReference{}, func(ctx context.Context, taskMode inspectioncore_contract.InspectionTaskModeType) (*googlecloudcommon_contract.ResourceNamesInput, error) {

	taskRunner := khictx.MustGetValue(ctx, inspectioncore_contract.TaskRunner)
	currentActiveResourceNameInputRequests := getCurrentActiveQueryIDsForResourceName(taskRunner)

	sharedMap := khictx.MustGetValue(ctx, inspectioncore_contract.InspectionSharedMap)
	resourceNamesInput := typedmap.GetOrSetFunc(sharedMap, resourceNamesInputKey, googlecloudcommon_contract.NewResourceNamesInput)

	metadata := khictx.MustGetValue(ctx, inspectioncore_contract.InspectionRunMetadata)
	formFields, found := typedmap.Get(metadata, inspectionmetadata.FormFieldSetMetadataKey)
	if !found {
		return nil, fmt.Errorf("failed to get form fields from run metadata")
	}

	requestInput := khictx.MustGetValue(ctx, inspectioncore_contract.InspectionTaskInput)

	queryForms := []inspectionmetadata.ParameterFormField{}
	for _, request := range currentActiveResourceNameInputRequests {
		queryInfo := resourceNamesInput.GetResourceNamesForQuery(ctx, request)
		defaultValue := strings.Join(queryInfo.DefaultResourceNames, " ")
		formFieldBase := inspectionmetadata.ParameterFormFieldBase{
			Priority:    0,
			ID:          queryInfo.GetInputID(),
			Type:        inspectionmetadata.Text,
			Label:       queryInfo.QueryID,
			Description: "",
			HintType:    inspectionmetadata.None,
			Hint:        "",
		}

		formInput, found := requestInput[queryInfo.GetInputID()]
		if found {
			resourceNamesFromInput := strings.Split(formInput.(string), " ")
			for i, resourceNameFromInput := range resourceNamesFromInput {
				resourceNameWithoutSurroundingSpace := strings.TrimSpace(resourceNameFromInput)
				err := googlecloud.ValidateResourceNameOnLogEntriesList(resourceNameWithoutSurroundingSpace)
				if err != nil {
					formFieldBase.HintType = inspectionmetadata.Error
					formFieldBase.Hint = fmt.Sprintf("%d: %s", i, err.Error())
					break
				}
			}
		}
		queryForms = append(queryForms, &inspectionmetadata.TextParameterFormField{
			ParameterFormFieldBase: formFieldBase,
			Default:                defaultValue,
			Suggestions:            queryInfo.DefaultResourceNames,
			ValidationTiming:       inspectionmetadata.Change,
		})
	}

	groupForm := inspectionmetadata.GroupParameterFormField{
		ParameterFormFieldBase: inspectionmetadata.ParameterFormFieldBase{
			Priority:    -1000000,
			ID:          googlecloudcommon_contract.InputLoggingFilterResourceNameTaskID.ReferenceIDString(),
			Type:        inspectionmetadata.Group,
			Label:       "Logging filter resource names (advanced)",
			Description: "Override these parameters when your logs are not on the same project of the cluster, or customize the log filter target resources.",
			HintType:    inspectionmetadata.None,
			Hint:        "",
		},
		Children:           queryForms,
		Collapsible:        true,
		CollapsedByDefault: true,
	}
	err := formFields.SetField(groupForm)
	if err != nil {
		return nil, err
	}

	return resourceNamesInput, nil
})

InputLoggingFilterResourceNameTask defines an inspection task that creates a form group for overriding log filter resource names for advanced users.

View Source
var InputProjectIdTask = formtask.NewTextFormTaskBuilder(googlecloudcommon_contract.InputProjectIdTaskID, googlecloudcommon_contract.PriorityForResourceIdentifierGroup+5000, "Project ID").
	WithDescription("The project ID containing logs of the cluster to query").
	WithValidatingTiming(inspectionmetadata.Blur).
	WithValidator(func(ctx context.Context, value string) (string, error) {
		if !projectIdValidator.Match([]byte(value)) {
			return "Project ID must match `^*[0-9a-z\\.:\\-]+$`", nil
		}
		return "", nil
	}).
	WithReadonlyFunc(func(ctx context.Context) (bool, error) {
		if parameters.Auth.FixedProjectID == nil {
			return false, nil
		}
		return *parameters.Auth.FixedProjectID != "", nil
	}).
	WithDefaultValueFunc(func(ctx context.Context, previousValues []string) (string, error) {
		if parameters.Auth.FixedProjectID != nil && *parameters.Auth.FixedProjectID != "" {
			return *parameters.Auth.FixedProjectID, nil
		}
		if len(previousValues) > 0 {
			return previousValues[0], nil
		}
		return "", nil
	}).
	WithConverter(func(ctx context.Context, value string) (string, error) {
		return strings.TrimSpace(value), nil
	}).
	Build()

InputProjectIdTask defines a form task for inputting the Google Cloud project ID.

View Source
var InputStartTimeTask = inspectiontaskbase.NewInspectionTask(googlecloudcommon_contract.InputStartTimeTaskID, []taskid.UntypedTaskReference{
	googlecloudcommon_contract.InputEndTimeTaskID.Ref(),
	googlecloudcommon_contract.InputDurationTaskID.Ref(),
}, func(ctx context.Context, taskMode inspectioncore_contract.InspectionTaskModeType) (time.Time, error) {
	endTime := coretask.GetTaskResult(ctx, googlecloudcommon_contract.InputEndTimeTaskID.Ref())
	duration := coretask.GetTaskResult(ctx, googlecloudcommon_contract.InputDurationTaskID.Ref())
	startTime := endTime.Add(-duration)

	metadataSet := khictx.MustGetValue(ctx, inspectioncore_contract.InspectionRunMetadata)

	header, found := typedmap.Get(metadataSet, inspectionmetadata.HeaderMetadataKey)
	if !found {
		return time.Time{}, fmt.Errorf("header metadata not found")
	}

	header.StartTimeUnixSeconds = startTime.Unix()
	header.EndTimeUnixSeconds = endTime.Unix()
	return startTime, nil
})

InputStartTimeTask defines an inspection task that calculates the start time of a query from the end time and duration.

LocationFetcherTask is the task to inject the reference to LocationFetcher.

LoggingFetcherTask is a task to inject the reference to LogFetcher.

Functions

func Register

func Register(registry coreinspection.InspectionTaskRegistry) error

Register registers all googlecloudcommon inspection tasks to the registry.

Types

This section is empty.

Jump to

Keyboard shortcuts

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