Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vttablet: debug/env page to change variables in real-time #7189

Merged
merged 5 commits into from
Dec 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions go/cmd/vttablet/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ var (
<a href="/debug/health">Query Service Health Check</a></br>
<a href="/livequeryz/">Real-time Queries</a></br>
<a href="/debug/status_details">JSON Status Details</a></br>
<a href="/debug/env">View/Change Environment variables</a></br>
</td>
</tr>
</table>
Expand Down
90 changes: 68 additions & 22 deletions go/vt/vttablet/endtoend/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package endtoend

import (
"fmt"
"sync"
"testing"
"time"
Expand All @@ -34,21 +35,9 @@ import (
"vitess.io/vitess/go/vt/vttablet/tabletserver/tabletenv"
)

// compareIntDiff returns an error if end[tag] != start[tag]+diff.
func compareIntDiff(t *testing.T, end map[string]interface{}, tag string, start map[string]interface{}, diff int) {
t.Helper()
verifyIntValue(t, end, tag, framework.FetchInt(start, tag)+diff)
}

// verifyIntValue returns an error if values[tag] != want.
func verifyIntValue(t *testing.T, values map[string]interface{}, tag string, want int) {
t.Helper()
require.Equal(t, want, framework.FetchInt(values, tag), tag)
}

func TestPoolSize(t *testing.T) {
defer framework.Server.SetPoolSize(framework.Server.PoolSize())
framework.Server.SetPoolSize(1)
revert := changeVar(t, "PoolSize", "1")
defer revert()

vstart := framework.DebugVars()
verifyIntValue(t, vstart, "ConnPoolCapacity", 1)
Expand All @@ -75,6 +64,22 @@ func TestPoolSize(t *testing.T) {
assert.LessOrEqual(t, want, got)
}

func TestStreamPoolSize(t *testing.T) {
revert := changeVar(t, "StreamPoolSize", "1")
defer revert()

vstart := framework.DebugVars()
verifyIntValue(t, vstart, "StreamConnPoolCapacity", 1)
}

func TestQueryCacheCapacity(t *testing.T) {
revert := changeVar(t, "QueryCacheCapacity", "1")
defer revert()

vstart := framework.DebugVars()
verifyIntValue(t, vstart, "QueryCacheCapacity", 1)
}

func TestDisableConsolidator(t *testing.T) {
totalConsolidationsTag := "Waits/Histograms/Consolidations/Count"
initial := framework.FetchInt(framework.DebugVars(), totalConsolidationsTag)
Expand All @@ -92,8 +97,8 @@ func TestDisableConsolidator(t *testing.T) {
afterOne := framework.FetchInt(framework.DebugVars(), totalConsolidationsTag)
assert.Equal(t, initial+1, afterOne, "expected one consolidation")

framework.Server.SetConsolidatorMode(tabletenv.Disable)
defer framework.Server.SetConsolidatorMode(tabletenv.Enable)
revert := changeVar(t, "Consolidator", tabletenv.Disable)
defer revert()
var wg2 sync.WaitGroup
wg2.Add(2)
go func() {
Expand Down Expand Up @@ -126,8 +131,8 @@ func TestConsolidatorReplicasOnly(t *testing.T) {
afterOne := framework.FetchInt(framework.DebugVars(), totalConsolidationsTag)
assert.Equal(t, initial+1, afterOne, "expected one consolidation")

framework.Server.SetConsolidatorMode(tabletenv.NotOnMaster)
defer framework.Server.SetConsolidatorMode(tabletenv.Enable)
revert := changeVar(t, "Consolidator", tabletenv.NotOnMaster)
defer revert()

// master should not do query consolidation
var wg2 sync.WaitGroup
Expand Down Expand Up @@ -201,8 +206,8 @@ func TestQueryPlanCache(t *testing.T) {
}

func TestMaxResultSize(t *testing.T) {
defer framework.Server.SetMaxResultSize(framework.Server.MaxResultSize())
framework.Server.SetMaxResultSize(2)
revert := changeVar(t, "MaxResultSize", "2")
defer revert()

client := framework.NewClient()
query := "select * from vitess_test"
Expand All @@ -217,8 +222,8 @@ func TestMaxResultSize(t *testing.T) {
}

func TestWarnResultSize(t *testing.T) {
defer framework.Server.SetWarnResultSize(framework.Server.WarnResultSize())
framework.Server.SetWarnResultSize(2)
revert := changeVar(t, "WarnResultSize", "2")
defer revert()
client := framework.NewClient()

originalWarningsResultsExceededCount := framework.FetchInt(framework.DebugVars(), "Warnings/ResultsExceeded")
Expand Down Expand Up @@ -252,3 +257,44 @@ func TestQueryTimeout(t *testing.T) {
verifyIntValue(t, vend, "QueryTimeout", int(100*time.Millisecond))
compareIntDiff(t, vend, "Kills/Queries", vstart, 1)
}

func changeVar(t *testing.T, name, value string) (revert func()) {
t.Helper()

vals := framework.FetchJSON("/debug/env?format=json")
initial, ok := vals[name]
if !ok {
t.Fatalf("%s not found in: %v", name, vals)
}
vals = framework.PostJSON("/debug/env?format=json", map[string]string{
"varname": name,
"value": value,
})
verifyMapValue(t, vals, name, value)
return func() {
vals = framework.PostJSON("/debug/env?format=json", map[string]string{
"varname": name,
"value": fmt.Sprintf("%v", initial),
})
verifyMapValue(t, vals, name, initial)
}
}

func verifyMapValue(t *testing.T, values map[string]interface{}, tag string, want interface{}) {
t.Helper()
val, ok := values[tag]
if !ok {
t.Fatalf("%s not found in: %v", tag, values)
}
assert.Equal(t, want, val)
}

func compareIntDiff(t *testing.T, end map[string]interface{}, tag string, start map[string]interface{}, diff int) {
t.Helper()
verifyIntValue(t, end, tag, framework.FetchInt(start, tag)+diff)
}

func verifyIntValue(t *testing.T, values map[string]interface{}, tag string, want int) {
t.Helper()
require.Equal(t, want, framework.FetchInt(values, tag), tag)
}
18 changes: 18 additions & 0 deletions go/vt/vttablet/endtoend/framework/debugvars.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)

Expand All @@ -37,6 +38,23 @@ func FetchJSON(urlPath string) map[string]interface{} {
return out
}

// PostJSON performs a post and fetches JSON content from the specified URL path and returns it
// as a map. The function returns an empty map on error.
func PostJSON(urlPath string, values map[string]string) map[string]interface{} {
urlValues := url.Values{}
for k, v := range values {
urlValues.Add(k, v)
}
out := map[string]interface{}{}
response, err := http.PostForm(fmt.Sprintf("%s%s", ServerAddress, urlPath), urlValues)
if err != nil {
return out
}
defer response.Body.Close()
_ = json.NewDecoder(response.Body).Decode(&out)
return out
}

// DebugVars parses /debug/vars and returns a map. The function returns
// an empty map on error.
func DebugVars() map[string]interface{} {
Expand Down
4 changes: 2 additions & 2 deletions go/vt/vttablet/endtoend/transaction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,8 @@ func TestTxPoolSize(t *testing.T) {
defer client1.Rollback()
verifyIntValue(t, framework.DebugVars(), "TransactionPoolAvailable", tabletenv.NewCurrentConfig().TxPool.Size-1)

defer framework.Server.SetTxPoolSize(framework.Server.TxPoolSize())
framework.Server.SetTxPoolSize(1)
revert := changeVar(t, "TxPoolSize", "1")
defer revert()
vend := framework.DebugVars()
verifyIntValue(t, vend, "TransactionPoolAvailable", 0)
verifyIntValue(t, vend, "TransactionPoolCapacity", 1)
Expand Down
137 changes: 137 additions & 0 deletions go/vt/vttablet/tabletserver/debugenv.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/*
Copyright 2020 The Vitess Authors.

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 tabletserver

import (
"encoding/json"
"fmt"
"html"
"net/http"
"strconv"
"text/template"

"vitess.io/vitess/go/acl"
"vitess.io/vitess/go/vt/log"
)

var (
debugEnvHeader = []byte(`
<thead><tr>
<th>Variable Name</th>
<th>Value</th>
<th>Action</th>
</tr></thead>
`)
debugEnvRow = template.Must(template.New("debugenv").Parse(`
<tr><form method="POST">
<td>{{.VarName}}</td>
<td>
<input type="hidden" name="varname" value="{{.VarName}}"></input>
<input type="text" name="value" value="{{.Value}}"></input>
</td>
<td><input type="submit" name="Action" value="Modify"></input></td>
</form></tr>
`))
)

type envValue struct {
VarName string
Value string
}

func debugEnvHandler(tsv *TabletServer, w http.ResponseWriter, r *http.Request) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably we should reject the request if the method is not POST

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I actually rely on this for my tests, by using GET. Is there a reason to disallow? Also, we seem to be allowing it in other places.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw that, If you change this, you will have to update the tests.

I think the reason is general HTTP conventions. In theory, GET requests could be cached and shouldn't mutate state.

I think that ideally, we should stop propagating this pattern. Once people start relying on the get will become even more difficult to change it.

if err := acl.CheckAccessHTTP(r, acl.ADMIN); err != nil {
acl.SendError(w, err)
return
}

var msg string
if r.Method == "POST" {
varname := r.FormValue("varname")
value := r.FormValue("value")
setIntVal := func(f func(int)) {
ival, err := strconv.Atoi(value)
if err != nil {
msg = fmt.Sprintf("Failed setting value for %v: %v", varname, err)
return
}
f(ival)
msg = fmt.Sprintf("Setting %v to: %v", varname, value)
}
switch varname {
case "PoolSize":
setIntVal(tsv.SetPoolSize)
case "StreamPoolSize":
setIntVal(tsv.SetStreamPoolSize)
case "TxPoolSize":
setIntVal(tsv.SetTxPoolSize)
case "QueryCacheCapacity":
setIntVal(tsv.SetQueryPlanCacheCap)
case "MaxResultSize":
setIntVal(tsv.SetMaxResultSize)
case "WarnResultSize":
setIntVal(tsv.SetWarnResultSize)
case "Consolidator":
tsv.SetConsolidatorMode(value)
msg = fmt.Sprintf("Setting %v to: %v", varname, value)
}
}

var vars []envValue
addIntVar := func(varname string, f func() int) {
vars = append(vars, envValue{
VarName: varname,
Value: fmt.Sprintf("%v", f()),
})
}
addIntVar("PoolSize", tsv.PoolSize)
addIntVar("StreamPoolSize", tsv.StreamPoolSize)
addIntVar("TxPoolSize", tsv.TxPoolSize)
addIntVar("QueryCacheCapacity", tsv.QueryPlanCacheCap)
addIntVar("MaxResultSize", tsv.MaxResultSize)
addIntVar("WarnResultSize", tsv.WarnResultSize)
vars = append(vars, envValue{
VarName: "Consolidator",
Value: tsv.ConsolidatorMode(),
})

format := r.FormValue("format")
if format == "json" {
mvars := make(map[string]string)
for _, v := range vars {
mvars[v.VarName] = v.Value
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(mvars)
return
}

// gridTable is reused from twopcz.go.
w.Write(gridTable)
w.Write([]byte("<h3>Internal Variables</h3>\n"))
if msg != "" {
w.Write([]byte(fmt.Sprintf("<b>%s</b><br /><br />\n", html.EscapeString(msg))))
}
w.Write(startTable)
w.Write(debugEnvHeader)
for _, v := range vars {
if err := debugEnvRow.Execute(w, v); err != nil {
log.Errorf("queryz: couldn't execute template: %v", err)
}
}
w.Write(endTable)
}
4 changes: 2 additions & 2 deletions go/vt/vttablet/tabletserver/query_engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ type QueryEngine struct {

strictTransTables bool

consolidatorMode string
consolidatorMode sync2.AtomicString
enableQueryPlanFieldCaching bool

// stats
Expand All @@ -175,7 +175,7 @@ func NewQueryEngine(env tabletenv.Env, se *schema.Engine) *QueryEngine {

qe.conns = connpool.NewPool(env, "ConnPool", config.OltpReadPool)
qe.streamConns = connpool.NewPool(env, "StreamConnPool", config.OlapReadPool)
qe.consolidatorMode = config.Consolidator
qe.consolidatorMode.Set(config.Consolidator)
qe.enableQueryPlanFieldCaching = config.CacheResultFields
qe.consolidator = sync2.NewConsolidator()
qe.txSerializer = txserializer.New(env)
Expand Down
2 changes: 1 addition & 1 deletion go/vt/vttablet/tabletserver/query_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,7 @@ func (qre *QueryExecutor) qFetch(logStats *tabletenv.LogStats, parsedQuery *sqlp
return nil, err
}
// Check tablet type.
if qre.tsv.qe.consolidatorMode == tabletenv.Enable || (qre.tsv.qe.consolidatorMode == tabletenv.NotOnMaster && qre.tabletType != topodatapb.TabletType_MASTER) {
if cm := qre.tsv.qe.consolidatorMode.Get(); cm == tabletenv.Enable || (cm == tabletenv.NotOnMaster && qre.tabletType != topodatapb.TabletType_MASTER) {
q, original := qre.tsv.qe.consolidator.Create(string(sqlWithoutComments))
if original {
defer q.Broadcast()
Expand Down
3 changes: 2 additions & 1 deletion go/vt/vttablet/tabletserver/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,9 @@ var (
<td width="25%" border="">
<a href="{{.Prefix}}/healthz">Health Check</a></br>
<a href="{{.Prefix}}/debug/health">Query Service Health Check</a></br>
<a href="/livequeryz/">Real-time Queries</a></br>
<a href="{{.Prefix}}/livequeryz/">Real-time Queries</a></br>
<a href="{{.Prefix}}/debug/status_details">JSON Status Details</a></br>
<a href="{{.Prefix}}/debug/env">View/Change Environment variables</a></br>
</td>
</tr>
</table>
Expand Down
Loading