chore: import upstream snapshot with attribution
CF: Deploy Dev Docs / deploy (push) Has been cancelled
Sync Labels / build (push) Has been cancelled
tests / unit tests (macos-latest) (push) Has been cancelled
tests / unit tests (windows-latest) (push) Has been cancelled
tests / unit tests (ubuntu-latest) (push) Has been cancelled
CF: Deploy Dev Docs / deploy (push) Has been cancelled
Sync Labels / build (push) Has been cancelled
tests / unit tests (macos-latest) (push) Has been cancelled
tests / unit tests (windows-latest) (push) Has been cancelled
tests / unit tests (ubuntu-latest) (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,214 @@
|
||||
// Copyright 2025 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cloudsqlpgupgradeprecheck
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
yaml "github.com/goccy/go-yaml"
|
||||
"github.com/googleapis/mcp-toolbox/internal/tools"
|
||||
"github.com/googleapis/mcp-toolbox/internal/util"
|
||||
"github.com/googleapis/mcp-toolbox/internal/util/parameters"
|
||||
sqladmin "google.golang.org/api/sqladmin/v1"
|
||||
)
|
||||
|
||||
const resourceType string = "postgres-upgrade-precheck"
|
||||
|
||||
func init() {
|
||||
if !tools.Register(resourceType, newConfig) {
|
||||
panic(fmt.Sprintf("tool type %q already registered", resourceType))
|
||||
}
|
||||
}
|
||||
|
||||
func newConfig(ctx context.Context, name string, decoder *yaml.Decoder) (tools.ToolConfig, error) {
|
||||
actual := Config{ConfigBase: tools.ConfigBase{Name: name}}
|
||||
if err := decoder.DecodeContext(ctx, &actual); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return actual, nil
|
||||
}
|
||||
|
||||
type compatibleSource interface {
|
||||
GetService(context.Context, string) (*sqladmin.Service, error)
|
||||
UseClientAuthorization() bool
|
||||
}
|
||||
|
||||
// Config defines the configuration for the precheck-upgrade tool.
|
||||
type Config struct {
|
||||
tools.ConfigBase `yaml:",inline"`
|
||||
Type string `yaml:"type" validate:"required"`
|
||||
Source string `yaml:"source" validate:"required"`
|
||||
Annotations *tools.ToolAnnotations `yaml:"annotations,omitempty"`
|
||||
}
|
||||
|
||||
// validate interface
|
||||
var _ tools.ToolConfig = Config{}
|
||||
|
||||
// ToolConfigType returns the type of the tool.
|
||||
func (cfg Config) ToolConfigType() string {
|
||||
return resourceType
|
||||
}
|
||||
|
||||
// Initialize initializes the tool from the configuration.
|
||||
func (cfg Config) Initialize(context.Context) (tools.Tool, error) {
|
||||
allParameters := parameters.Parameters{
|
||||
parameters.NewStringParameter("project", "The project ID"),
|
||||
parameters.NewStringParameter("instance", "The name of the instance to check"),
|
||||
parameters.NewStringParameter("targetDatabaseVersion", "The target PostgreSQL version for the upgrade (e.g., POSTGRES_18). If not specified, defaults to the PostgreSQL 18.", parameters.WithStringDefault("POSTGRES_18")),
|
||||
}
|
||||
|
||||
if cfg.Description == "" {
|
||||
cfg.Description = "Analyzes a Cloud SQL PostgreSQL instance for major version upgrade readiness. Results are provided to guide customer actions:\n" +
|
||||
"ERROR: Action Required. These are critical issues blocking the upgrade. Customers must resolve these using the provided actions_required steps before attempting the upgrade.\n" +
|
||||
"WARNING: Review Recommended. These are potential issues. Customers should review the message and actions_required. While not blocking, addressing these is advised to prevent future problems or unexpected behavior post-upgrade.\n" +
|
||||
"INFO: No Action Needed. Informational messages only. This pre-check helps customers proactively fix problems, preventing upgrade failures and ensuring a smoother transition."
|
||||
}
|
||||
return Tool{
|
||||
BaseTool: tools.NewBaseTool(
|
||||
cfg,
|
||||
tools.GetAnnotationsOrDefault(cfg.Annotations, tools.NewReadOnlyAnnotations),
|
||||
tools.Manifest{Description: cfg.Description, Parameters: allParameters.Manifest(), AuthRequired: cfg.AuthRequired},
|
||||
allParameters,
|
||||
),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Tool represents the precheck-upgrade tool.
|
||||
type Tool struct {
|
||||
tools.BaseTool[Config]
|
||||
}
|
||||
|
||||
// PreCheckResultItem holds the details of a single check result.
|
||||
type PreCheckResultItem struct {
|
||||
Message string `json:"message"`
|
||||
MessageType string `json:"messageType"` // INFO, WARNING, ERROR
|
||||
ActionsRequired []string `json:"actionsRequired"`
|
||||
}
|
||||
|
||||
// PreCheckAPIResponse holds the array of pre-check results.
|
||||
type PreCheckAPIResponse struct {
|
||||
Items []PreCheckResultItem `json:"preCheckResponse"`
|
||||
}
|
||||
|
||||
// Helper function to convert from []*sqladmin.PreCheckResponse to []PreCheckResultItem
|
||||
func convertResults(items []*sqladmin.PreCheckResponse) []PreCheckResultItem {
|
||||
if len(items) == 0 { // Handle nil or empty slice
|
||||
return []PreCheckResultItem{}
|
||||
}
|
||||
results := make([]PreCheckResultItem, len(items))
|
||||
for i, item := range items {
|
||||
results[i] = PreCheckResultItem{
|
||||
Message: item.Message,
|
||||
MessageType: item.MessageType,
|
||||
ActionsRequired: item.ActionsRequired,
|
||||
}
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
func (t Tool) ToConfig() tools.ToolConfig {
|
||||
return t.Cfg
|
||||
}
|
||||
|
||||
// Invoke executes the tool's logic.
|
||||
func (t Tool) Invoke(ctx context.Context, resourceMgr tools.SourceProvider, params parameters.ParamValues, accessToken tools.AccessToken) (any, util.ToolboxError) {
|
||||
source, err := tools.GetCompatibleSource[compatibleSource](resourceMgr, t.Cfg.Source, t.Cfg.Name, t.Cfg.Type)
|
||||
if err != nil {
|
||||
return nil, util.NewClientServerError("source used is not compatible with the tool", http.StatusInternalServerError, err)
|
||||
}
|
||||
|
||||
paramsMap := params.AsMap()
|
||||
|
||||
project, ok := paramsMap["project"].(string)
|
||||
if !ok || project == "" {
|
||||
return nil, util.NewAgentError("missing or empty 'project' parameter", nil)
|
||||
}
|
||||
instanceName, ok := paramsMap["instance"].(string)
|
||||
if !ok || instanceName == "" {
|
||||
return nil, util.NewAgentError("missing or empty 'instance' parameter", nil)
|
||||
}
|
||||
targetVersion, ok := paramsMap["targetDatabaseVersion"].(string)
|
||||
if !ok || targetVersion == "" {
|
||||
// This should not happen due to the default value
|
||||
return nil, util.NewAgentError("missing or empty 'targetDatabaseVersion' parameter", nil)
|
||||
}
|
||||
|
||||
service, err := source.GetService(ctx, string(accessToken))
|
||||
if err != nil {
|
||||
return nil, util.ProcessGcpError(err)
|
||||
}
|
||||
|
||||
reqBody := &sqladmin.InstancesPreCheckMajorVersionUpgradeRequest{
|
||||
PreCheckMajorVersionUpgradeContext: &sqladmin.PreCheckMajorVersionUpgradeContext{
|
||||
TargetDatabaseVersion: targetVersion,
|
||||
},
|
||||
}
|
||||
|
||||
call := service.Instances.PreCheckMajorVersionUpgrade(project, instanceName, reqBody).Context(ctx)
|
||||
op, err := call.Do()
|
||||
if err != nil {
|
||||
return nil, util.ProcessGcpError(err)
|
||||
}
|
||||
|
||||
const pollTimeout = 20 * time.Second
|
||||
cutoffTime := time.Now().Add(pollTimeout)
|
||||
|
||||
for time.Now().Before(cutoffTime) {
|
||||
currentOp, err := service.Operations.Get(project, op.Name).Context(ctx).Do()
|
||||
if err != nil {
|
||||
return nil, util.ProcessGcpError(err)
|
||||
}
|
||||
|
||||
if currentOp.Status == "DONE" {
|
||||
if currentOp.Error != nil && len(currentOp.Error.Errors) > 0 {
|
||||
errMsg := fmt.Sprintf("pre-check operation LRO failed: %s", currentOp.Error.Errors[0].Message)
|
||||
if currentOp.Error.Errors[0].Code != "" {
|
||||
errMsg = fmt.Sprintf("%s (Code: %s)", errMsg, currentOp.Error.Errors[0].Code)
|
||||
}
|
||||
return nil, util.NewClientServerError(errMsg, http.StatusInternalServerError, fmt.Errorf("pre-check operation failed with error: %s", errMsg))
|
||||
}
|
||||
|
||||
var preCheckItems []*sqladmin.PreCheckResponse
|
||||
if currentOp.PreCheckMajorVersionUpgradeContext != nil {
|
||||
preCheckItems = currentOp.PreCheckMajorVersionUpgradeContext.PreCheckResponse
|
||||
}
|
||||
// convertResults handles nil or empty preCheckItems
|
||||
return PreCheckAPIResponse{Items: convertResults(preCheckItems)}, nil
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, util.NewClientServerError("timed out waiting for operation", http.StatusRequestTimeout, ctx.Err())
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
}
|
||||
return op, nil
|
||||
}
|
||||
|
||||
// Authorized checks if the tool is authorized.
|
||||
func (t Tool) Authorized(verifiedAuthServices []string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (t Tool) RequiresClientAuthorization(resourceMgr tools.SourceProvider) (bool, error) {
|
||||
source, err := tools.GetCompatibleSource[compatibleSource](resourceMgr, t.Cfg.Source, t.Cfg.Name, t.Cfg.Type)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return source.UseClientAuthorization(), nil
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// Copyright 2025 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cloudsqlpgupgradeprecheck_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/googleapis/mcp-toolbox/internal/server"
|
||||
"github.com/googleapis/mcp-toolbox/internal/testutils"
|
||||
"github.com/googleapis/mcp-toolbox/internal/tools"
|
||||
"github.com/googleapis/mcp-toolbox/internal/tools/cloudsqlpg/cloudsqlpgupgradeprecheck"
|
||||
)
|
||||
|
||||
func TestParseFromYaml(t *testing.T) {
|
||||
ctx, err := testutils.ContextWithNewLogger()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %s", err)
|
||||
}
|
||||
tcs := []struct {
|
||||
desc string
|
||||
in string
|
||||
want server.ToolConfigs
|
||||
}{
|
||||
{
|
||||
desc: "basic precheck example",
|
||||
in: `
|
||||
kind: tool
|
||||
name: precheck-upgrade-tool
|
||||
type: postgres-upgrade-precheck
|
||||
description: a precheck test description
|
||||
source: some-admin-source
|
||||
authRequired:
|
||||
- https://www.googleapis.com/auth/cloud-platform
|
||||
`,
|
||||
want: server.ToolConfigs{
|
||||
"precheck-upgrade-tool": cloudsqlpgupgradeprecheck.Config{
|
||||
ConfigBase: tools.ConfigBase{
|
||||
Name: "precheck-upgrade-tool",
|
||||
Description: "a precheck test description",
|
||||
AuthRequired: []string{"https://www.googleapis.com/auth/cloud-platform"},
|
||||
},
|
||||
Type: "postgres-upgrade-precheck",
|
||||
Source: "some-admin-source",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "precheck example with no auth",
|
||||
in: `
|
||||
kind: tool
|
||||
name: precheck-upgrade-tool-no-auth
|
||||
type: postgres-upgrade-precheck
|
||||
description: a precheck test description no auth
|
||||
source: other-admin-source
|
||||
`,
|
||||
want: server.ToolConfigs{
|
||||
"precheck-upgrade-tool-no-auth": cloudsqlpgupgradeprecheck.Config{
|
||||
ConfigBase: tools.ConfigBase{
|
||||
Name: "precheck-upgrade-tool-no-auth",
|
||||
Description: "a precheck test description no auth",
|
||||
AuthRequired: []string{},
|
||||
},
|
||||
Type: "postgres-upgrade-precheck",
|
||||
Source: "other-admin-source",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tc := range tcs {
|
||||
t.Run(tc.desc, func(t *testing.T) {
|
||||
_, _, _, got, _, _, err := server.UnmarshalResourceConfig(ctx, testutils.FormatYaml(tc.in))
|
||||
if err != nil {
|
||||
t.Fatalf("unable to unmarshal: %s", err)
|
||||
}
|
||||
if diff := cmp.Diff(tc.want, got); diff != "" {
|
||||
t.Fatalf("incorrect parse: diff (-want +got):\n%s", diff)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user