diff --git a/canal/config.go b/canal/config.go index 35df54632..583906ac5 100644 --- a/canal/config.go +++ b/canal/config.go @@ -105,7 +105,8 @@ type Config struct { // Set Dialer Dialer client.Dialer - // Set Localhost + // Set the hostname that is used when registering as replica. This is similar to `report_host` in MySQL. + // This will be truncated if it is longer than 255 characters. Localhost string // EventCacheCount is the capacity of the BinlogStreamer internal event channel. diff --git a/replication/binlogsyncer.go b/replication/binlogsyncer.go index 3ef4fb63a..612229926 100644 --- a/replication/binlogsyncer.go +++ b/replication/binlogsyncer.go @@ -573,13 +573,17 @@ func (b *BinlogSyncer) writeBinlogDumpMariadbGTIDCommand(gset mysql.GTIDSet) err return b.writeBinlogDumpCommand(mysql.Position{Name: "", Pos: 0}) } -// localHostname returns the hostname that register slave would register as. +// localHostname returns the hostname that register replica would register as. +// this gets truncated to 255 bytes. func (b *BinlogSyncer) localHostname() string { - if len(b.cfg.Localhost) == 0 { - h, _ := os.Hostname() + h := b.cfg.Localhost + if len(h) == 0 { + h, _ = os.Hostname() + } + if len(h) <= 255 { return h } - return b.cfg.Localhost + return h[:255] } func (b *BinlogSyncer) writeRegisterSlaveCommand() error { diff --git a/replication/binlogsyncer_test.go b/replication/binlogsyncer_test.go new file mode 100644 index 000000000..9895673e3 --- /dev/null +++ b/replication/binlogsyncer_test.go @@ -0,0 +1,50 @@ +package replication + +import ( + "os" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestLocalHostname(t *testing.T) { + b := BinlogSyncer{ + cfg: BinlogSyncerConfig{ + Localhost: "foobar", + }, + } + + require.Equal(t, "foobar", b.localHostname()) +} + +func TestLocalHostname_long(t *testing.T) { + b := BinlogSyncer{ + cfg: BinlogSyncerConfig{ + Localhost: strings.Repeat("x", 255), + }, + } + + require.Equal(t, 255, len(b.localHostname())) +} + +func TestLocalHostname_toolong(t *testing.T) { + b := BinlogSyncer{ + cfg: BinlogSyncerConfig{ + Localhost: strings.Repeat("x", 300), + }, + } + + require.Equal(t, 255, len(b.localHostname())) +} + +func TestLocalHostname_os(t *testing.T) { + b := BinlogSyncer{ + cfg: BinlogSyncerConfig{ + Localhost: "", + }, + } + + h, _ := os.Hostname() + require.Equal(t, h, b.localHostname()) +}