Files
tasks/tools/tdbg/app.go
Michael SnowdenandGitHub 8f87badf69 Decode DLQ tasks in tdbg (#5045)
<!-- Describe what has changed in this PR -->
**What changed?**
I added pluggable logic to decode DLQ tasks in tdbg. The default
behavior uses the predefined set of categories in the server,
deserializes them into protos, and then uses jsonpb to marshal them.
However, for deployments with custom task categories, there is an option
of extending this behavior.

Registering a custom task category will look something like this:

```go
package main

import (
	"os"

	"github.com/gogo/protobuf/proto"
	commonpb "go.temporal.io/api/common/v1"
	"go.temporal.io/server/service/history/tasks"
	"go.temporal.io/server/tools/tdbg"
)

type (
	myTaskDeserializer struct {
		baseDeserializer tdbg.PredefinedTaskBlobDeserializer // the zero value is valid
	}
	myTaskCategoryRegistry struct {
		baseRegistry tasks.TaskCategoryRegistry
	}
)

var (
	myTaskCategory = tasks.Category{
		// ...
	}
)

func (m myTaskDeserializer) Deserialize(taskCategoryID int, blob commonpb.DataBlob) (proto.Message, error) {
	if taskCategoryID == myTaskCategory.ID() {
		panic("TODO")
	}
	return m.baseDeserializer.Deserialize(taskCategoryID, blob)
}

func (m myTaskCategoryRegistry) GetCategoryByID(id int) (tasks.Category, bool) {
	if id == myTaskCategory.ID() {
		return myTaskCategory, true
	}
	return m.baseRegistry.GetCategoryByID(id)
}

func (m myTaskCategoryRegistry) GetCategories() map[int]tasks.Category {
	categories := m.baseRegistry.GetCategories()
	categories[myTaskCategory.ID()] = myTaskCategory
	return categories
}

func main() {
	_ = tdbg.NewCliApp(func(params *tdbg.Params) {
		params.TaskBlobEncoder = tdbg.NewProtoTaskBlobEncoder(myTaskDeserializer{})
		params.TaskCategoryRegistry = myTaskCategoryRegistry{
			baseRegistry: tasks.NewDefaultTaskCategoryRegistry(),
		}
	}).Run(os.Args)
}
```

<!-- Tell your future self why have you made these changes -->
**Why?**
Before this change, tasks looked like this:

```json
{
  "metadata": {
    "messageId": "0"
  },
  "payload": {
    "shardId": 1,
    "blob": {
      "encodingType": "Proto3",
      "data": "CiRhZjllOTY4Ni0yNThiLTRiOGYtYWU2ZC0xMWNhMjIzZWQ1ZGYSO2RscS10ZXN0LXRlcm1pbmFsLXdmdHMtNGJlN2RlMTctZWQ4Yy00NjliLWExOGMtYmExMjJmZmI5YzE2GiQ0YTI4YzA1ZC1kZGIyLTQxYzYtOWQ0Ni0xYjhkYTU2OWFlNTQgAyokYWY5ZTk2ODYtMjU4Yi00YjhmLWFlNmQtMTFjYTIyM2VkNWRmQhNkbHEtdGVzdC10YXNrLXF1ZXVlUAJghIBAagwIm6ftqQYQkLiC4AE="
    }
  }
}
```

Now they're much more informative:
```json
{
  "message_id": 0,
  "shard_id": 3,
  "payload": {
    "namespace_id": "0d911dda-4c83-4890-9a00-aa4b709bfea6",
    "workflow_id": "dlq-test-terminal-wfts-b6871484-2840-40b4-9460-c8289ee8e178",
    "run_id": "1d8dfa7c-09e5-4845-a16f-69eed57fec9d",
    "task_type": "TransferWorkflowTask",
    "target_namespace_id": "0d911dda-4c83-4890-9a00-aa4b709bfea6",
    "target_workflow_id": "",
    "target_run_id": "",
    "task_queue": "dlq-test-task-queue",
    "target_child_workflow_only": false,
    "scheduled_event_id": "2",
    "version": "0",
    "task_id": "1048580",
    "visibility_time": "2023-10-27T06:08:08.993945Z",
    "delete_after_close": false
  }
}
```

<!-- How have you verified this change? Tested locally? Added a unit
test? Checked in staging env? -->
**How did you test it?**
There's quite a few tests which verify that the output contains task
details now without further parsing of any "data" field. In addition, I
did some manual testing to inspect the output.

<!-- Assuming the worst case, what can be broken when deploying this
change to production? -->
**Potential risks**

<!-- Is this PR a hotfix candidate or require that a notification be
sent to the broader community? (Yes/No) -->
**Is hotfix candidate?**
2023-10-28 04:21:45 +00:00

166 lines
5.1 KiB
Go

// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package tdbg
import (
"fmt"
"io"
"os"
"runtime/debug"
"github.com/urfave/cli/v2"
"go.temporal.io/server/common/headers"
"go.temporal.io/server/service/history/tasks"
"github.com/temporalio/tctl-kit/pkg/color"
)
type (
// Params which are customizable for the CLI application.
Params struct {
// ClientFactory creates Temporal service clients for tdbg to use.
ClientFactory ClientFactory
// TaskCategoryRegistry is used to determine which task categories are available for tdbg to use.
TaskCategoryRegistry tasks.TaskCategoryRegistry
// Writer is used to write output from tdbg. The default is os.Stdout.
Writer io.Writer
// TaskBlobEncoder is needed for custom task serialization. The default uses PredefinedTaskBlobDeserializer.
TaskBlobEncoder TaskBlobEncoder
}
// Option modifies the Params for tdbg.
Option func(params *Params)
)
// NewCliApp instantiates a new instance of the CLI application.
func NewCliApp(opts ...Option) *cli.App {
params := Params{
ClientFactory: NewClientFactory(),
TaskCategoryRegistry: tasks.NewDefaultTaskCategoryRegistry(),
Writer: os.Stdout,
TaskBlobEncoder: NewProtoTaskBlobEncoder(NewPredefinedTaskBlobDeserializer()),
}
for _, opt := range opts {
opt(&params)
}
app := cli.NewApp()
app.Name = "tdbg"
app.Usage = "A command-line tool for Temporal server debugging"
app.Version = headers.ServerVersion
app.Flags = []cli.Flag{
&cli.StringFlag{
Name: FlagAddress,
Value: "",
Usage: "host:port for Temporal frontend service",
EnvVars: []string{"TEMPORAL_CLI_ADDRESS"},
},
&cli.StringFlag{
Name: FlagNamespace,
Aliases: FlagNamespaceAlias,
Value: "default",
Usage: "Temporal workflow namespace",
EnvVars: []string{"TEMPORAL_CLI_NAMESPACE"},
},
&cli.IntFlag{
Name: FlagContextTimeout,
Aliases: FlagContextTimeoutAlias,
Value: defaultContextTimeoutInSeconds,
Usage: "Optional timeout for context of RPC call in seconds",
EnvVars: []string{"TEMPORAL_CONTEXT_TIMEOUT"},
},
&cli.BoolFlag{
Name: FlagYes,
Usage: "Automatically confirm all prompts",
},
&cli.StringFlag{
Name: FlagTLSCertPath,
Value: "",
Usage: "Path to x509 certificate",
EnvVars: []string{"TEMPORAL_CLI_TLS_CERT"},
},
&cli.StringFlag{
Name: FlagTLSKeyPath,
Value: "",
Usage: "Path to private key",
EnvVars: []string{"TEMPORAL_CLI_TLS_KEY"},
},
&cli.StringFlag{
Name: FlagTLSCaPath,
Value: "",
Usage: "Path to server CA certificate",
EnvVars: []string{"TEMPORAL_CLI_TLS_CA"},
},
&cli.BoolFlag{
Name: FlagTLSDisableHostVerification,
Usage: "Disable tls host name verification (tls must be enabled)",
EnvVars: []string{"TEMPORAL_CLI_TLS_DISABLE_HOST_VERIFICATION"},
},
&cli.StringFlag{
Name: FlagTLSServerName,
Value: "",
Usage: "Override for target server name",
EnvVars: []string{"TEMPORAL_CLI_TLS_SERVER_NAME"},
},
&cli.StringFlag{
Name: color.FlagColor,
Usage: fmt.Sprintf("when to use color: %v, %v, %v.", color.Auto, color.Always, color.Never),
Value: string(color.Auto),
},
}
prompterFactory := NewPrompterFactory()
app.Commands = getCommands(
params.ClientFactory,
NewDLQServiceProvider(
params.ClientFactory,
params.TaskBlobEncoder,
params.TaskCategoryRegistry,
params.Writer,
prompterFactory,
),
params.TaskCategoryRegistry,
prompterFactory,
params.TaskBlobEncoder,
params.Writer,
)
app.ExitErrHandler = handleError
return app
}
func handleError(c *cli.Context, err error) {
if err == nil {
return
}
_, _ = fmt.Fprintf(os.Stderr, "%s %+v\n", color.Red(c, "Error:"), err)
if os.Getenv(showErrorStackEnv) != `` {
_, _ = fmt.Fprintln(os.Stderr, color.Magenta(c, "Stack trace:"))
debug.PrintStack()
} else {
_, _ = fmt.Fprintf(os.Stderr, "('export %s=1' to see stack traces)\n", showErrorStackEnv)
}
cli.OsExiter(1)
}