istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/ctrlz/topics/mem.go (about)

     1  // Copyright Istio Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package topics defines several canonical ControlZ topics.
    16  package topics
    17  
    18  import (
    19  	"net/http"
    20  	"runtime"
    21  
    22  	"istio.io/istio/pkg/ctrlz/fw"
    23  	"istio.io/istio/pkg/ctrlz/topics/assets"
    24  )
    25  
    26  type memTopic struct{}
    27  
    28  // MemTopic returns a ControlZ topic that allows visualization of process memory usage.
    29  func MemTopic() fw.Topic {
    30  	return memTopic{}
    31  }
    32  
    33  func (memTopic) Title() string {
    34  	return "Memory Usage"
    35  }
    36  
    37  func (memTopic) Prefix() string {
    38  	return "mem"
    39  }
    40  
    41  func (memTopic) Activate(context fw.TopicContext) {
    42  	tmpl := assets.ParseTemplate(context.Layout(), "templates/mem.html")
    43  
    44  	_ = context.HTMLRouter().StrictSlash(true).NewRoute().Path("/").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    45  		ms := &runtime.MemStats{}
    46  		runtime.ReadMemStats(ms)
    47  		fw.RenderHTML(w, tmpl, ms)
    48  	})
    49  
    50  	_ = context.JSONRouter().StrictSlash(true).NewRoute().Methods("GET").Path("/").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    51  		ms := &runtime.MemStats{}
    52  		runtime.ReadMemStats(ms)
    53  		fw.RenderJSON(w, http.StatusOK, ms)
    54  	})
    55  
    56  	_ = context.JSONRouter().StrictSlash(true).NewRoute().Methods("PUT").Path("/forcecollection").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    57  		runtime.GC()
    58  		w.WriteHeader(http.StatusAccepted)
    59  	})
    60  }