From 13bd28838a128b6f85cd0c5846c8e61a6f2be74d Mon Sep 17 00:00:00 2001 From: Artem Babii Date: Tue, 27 Aug 2024 16:30:33 +0300 Subject: [PATCH] first commit --- .github/workflows/release.yaml | 28 ++++ LICENSE | 21 +++ README.md | 41 ++++++ cmd/root.go | 233 +++++++++++++++++++++++++++++++++ go.mod | 34 +++++ go.sum | 61 +++++++++ main.go | 7 + 7 files changed, 425 insertions(+) create mode 100644 .github/workflows/release.yaml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 cmd/root.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 main.go diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml new file mode 100644 index 0000000..b0fe116 --- /dev/null +++ b/.github/workflows/release.yaml @@ -0,0 +1,28 @@ +name: release + +on: + push: + tags: + - "*" + +jobs: + release: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v5 + with: + go-version: "1.22.6" + - run: | + go get . + - run: | + GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o htp_linux_amd64 + - run: | + GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w" -o htp_darwin_amd64 + - run: | + GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w" -o htp_darwin_arm64 + - uses: ncipollo/release-action@v1 + with: + artifacts: "htp*" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..97022e5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Artem Babii + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..480cc67 --- /dev/null +++ b/README.md @@ -0,0 +1,41 @@ +# htp + +HTTP Tick Ping (htp) - a tool to send HTTP probe requests at regular intervals + +The requests are sent at the exact scheduled time depending on the set interval, even if the previous requests have not completed yet. This might help determine how long the service exposed on the target URL stays unavailable from the user's perspective after e.g. k8s pod or web server restart. + +## Usage + +``` +A tool to send HTTP probe requests at regular intervals + +Usage: + htp URL [flags] + +Flags: + -i, --interval int interval between requests in milliseconds (default 1000) + -l, --limit int number of requests to make (default unlimited) + -t, --tail int number of requests to tail (default 25) + -g, --get use GET method (default HEAD) + -k, --insecure allow insecure connections + -h, --help help for htp + -v, --version version for htp +``` + +## Example + +```sh +❯ htp https://google.com -l 10 +HEAD http://google.com every 1000ms + +1: start=09:35:55.830, duration=262ms, end=09:35:56.092 [200] http://www.google.com/ +2: start=09:35:56.831, duration=105ms, end=09:35:56.936 [200] http://www.google.com/ +3: start=09:35:57.830, duration=103ms, end=09:35:57.934 [200] http://www.google.com/ +4: start=09:35:58.831, duration=104ms, end=09:35:58.935 [200] http://www.google.com/ +5: start=09:35:59.831, duration=106ms, end=09:35:59.937 [200] http://www.google.com/ +6: start=09:36:00.831, duration=103ms, end=09:36:00.933 [200] http://www.google.com/ +7: start=09:36:01.831, duration=105ms, end=09:36:01.936 [200] http://www.google.com/ +8: start=09:36:02.830, duration=103ms, end=09:36:02.934 [200] http://www.google.com/ +9: start=09:36:03.830, duration=103ms, end=09:36:03.933 [200] http://www.google.com/ +10: start=09:36:04.831, duration=127ms, end=09:36:04.958 [200] http://www.google.com/ +``` diff --git a/cmd/root.go b/cmd/root.go new file mode 100644 index 0000000..64eec8c --- /dev/null +++ b/cmd/root.go @@ -0,0 +1,233 @@ +package cmd + +import ( + "crypto/tls" + "fmt" + "log" + "net/http" + "net/url" + "os" + "slices" + "strconv" + "strings" + "sync" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/fatih/color" + "github.com/spf13/cobra" +) + +type options struct { + intervalMs int + requestLimit int + tailLines int + useGet bool + allowInsecure bool +} + +type probe struct { + id int + start time.Time + duration time.Duration + end time.Time + status int + url string + err error +} + +type model struct { + probes []probe + exit bool +} + +type probeMsg probe + +var opts options + +var rootCmd = &cobra.Command{ + Use: "htp URL", + Long: "A tool to send HTTP probe requests at regular intervals", + Version: "v0.0.1", + Args: cobra.ExactArgs(1), + Run: main, +} + +func Execute() { + if err := rootCmd.Execute(); err != nil { + os.Exit(1) + } +} + +func init() { + log.SetFlags(0) + log.SetPrefix("Error: ") + rootCmd.Flags().IntVarP(&opts.intervalMs, "interval", "i", 1000, "interval between requests in milliseconds") + rootCmd.Flags().IntVarP(&opts.requestLimit, "limit", "l", 0, "number of requests to make (default unlimited)") + rootCmd.Flags().IntVarP(&opts.tailLines, "tail", "t", 25, "number of requests to tail") + rootCmd.Flags().BoolVarP(&opts.useGet, "get", "g", false, "use GET method (default HEAD)") + rootCmd.Flags().BoolVarP(&opts.allowInsecure, "insecure", "k", false, "allow insecure connections") + rootCmd.Flags().SortFlags = false +} + +func colorStatusCode(code int) string { + stringCode := strconv.Itoa(code) + switch { + case strings.HasPrefix(stringCode, "2"): + return color.GreenString(stringCode) + case strings.HasPrefix(stringCode, "4"): + return color.YellowString(stringCode) + case strings.HasPrefix(stringCode, "5"): + return color.RedString(stringCode) + default: + return stringCode + } +} + +func setHttpMethod() string { + if opts.useGet { + return "GET" + } else { + return "HEAD" + } +} + +func renderOutput(m model, offset int) string { + var output string + for _, probe := range m.probes[offset:] { + switch { + case probe.err != nil: + output += fmt.Sprintf("%d: start=%s, duration=%s, end=%s [%s] %v\n", + probe.id, + probe.start.Format("15:04:05.000"), + probe.duration.Round(time.Millisecond), + probe.end.Format("15:04:05.000"), + color.RedString("ERROR"), + probe.err, + ) + case probe.status == 0: + output += fmt.Sprintf("%d:\n", probe.id) + default: + output += fmt.Sprintf("%d: start=%s, duration=%s, end=%s [%s] %s\n", + probe.id, + probe.start.Format("15:04:05.000"), + probe.duration.Round(time.Millisecond), + probe.end.Format("15:04:05.000"), + colorStatusCode(probe.status), + color.BlackString(probe.url), + ) + } + } + return output +} + +func probeUrl(c *http.Client, id int, target *url.URL, method string) tea.Msg { + req, err := http.NewRequest(method, target.String(), http.NoBody) + if err != nil { + log.Fatalf("%v\n", err) + } + start := time.Now() + resp, err := c.Do(req) + duration := time.Since(start) + end := start.Add(duration) + if err != nil { + return probeMsg{ + id: id, + start: start, + duration: duration, + end: end, + err: err, + } + } + defer resp.Body.Close() + return probeMsg{ + id: id, + start: start, + duration: duration, + end: end, + status: resp.StatusCode, + url: resp.Request.URL.String(), + } +} + +func (m model) Init() tea.Cmd { + return nil +} + +func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.KeyMsg: + if k := msg.String(); k == "ctrl+c" || k == "q" || k == "esc" { + m.exit = true + return m, tea.Quit + } + case probeMsg: + if i := slices.IndexFunc(m.probes, func(r probe) bool { return r.id == msg.id }); i >= 0 { + m.probes[i] = probe(msg) + } else { + m.probes = append(m.probes, probe(msg)) + } + } + return m, nil +} + +func (m model) View() string { + if m.exit { + return "" + } + offset := len(m.probes) - opts.tailLines + if offset < 0 { + offset = 0 + } + return renderOutput(m, offset) +} + +func main(cmd *cobra.Command, args []string) { + target, err := url.ParseRequestURI(args[0]) + if err != nil { + log.Fatalf("%v\n", err) + } + method := setHttpMethod() + + tr := &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: opts.allowInsecure}, + } + c := &http.Client{Transport: tr} + p := tea.NewProgram(model{}) + t := time.NewTicker(time.Duration(opts.intervalMs) * time.Millisecond) + + fmt.Printf("%s %s every %dms\n\n", method, target, opts.intervalMs) + + go func() { + var wg sync.WaitGroup + defer t.Stop() + id := 1 + for { + if opts.requestLimit != 0 && id > opts.requestLimit { + break + } + p.Send(probeMsg{id: id}) + wg.Add(1) + go func(id int) { + defer wg.Done() + p.Send(probeUrl(c, id, target, method)) + }(id) + id++ + <-t.C + } + wg.Wait() + p.Send(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'q'}}) + }() + + result, err := p.Run() + if err != nil { + log.Fatalf("%v\n", err) + } + + resultModel, ok := result.(model) + if !ok { + log.Fatalf("%v\n", err) + } + + fmt.Printf(renderOutput(resultModel, 0)) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..88ff796 --- /dev/null +++ b/go.mod @@ -0,0 +1,34 @@ +module htp + +go 1.22.6 + +require ( + github.com/charmbracelet/bubbletea v0.27.1 + github.com/fatih/color v1.17.0 + github.com/spf13/cobra v1.8.1 +) + +require ( + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/charmbracelet/lipgloss v0.13.0 // indirect + github.com/charmbracelet/x/ansi v0.1.4 // indirect + github.com/charmbracelet/x/input v0.1.0 // indirect + github.com/charmbracelet/x/term v0.1.1 // indirect + github.com/charmbracelet/x/windows v0.1.0 // indirect + github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-localereader v0.0.1 // indirect + github.com/mattn/go-runewidth v0.0.15 // indirect + github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/muesli/termenv v0.15.2 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + golang.org/x/sync v0.8.0 // indirect + golang.org/x/sys v0.24.0 // indirect + golang.org/x/text v0.3.8 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..b36977d --- /dev/null +++ b/go.sum @@ -0,0 +1,61 @@ +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= +github.com/charmbracelet/bubbletea v0.27.1 h1:/yhaJKX52pxG4jZVKCNWj/oq0QouPdXycriDRA6m6r8= +github.com/charmbracelet/bubbletea v0.27.1/go.mod h1:xc4gm5yv+7tbniEvQ0naiG9P3fzYhk16cTgDZQQW6YE= +github.com/charmbracelet/lipgloss v0.13.0 h1:4X3PPeoWEDCMvzDvGmTajSyYPcZM4+y8sCA/SsA3cjw= +github.com/charmbracelet/lipgloss v0.13.0/go.mod h1:nw4zy0SBX/F/eAO1cWdcvy6qnkDUxr8Lw7dvFrAIbbY= +github.com/charmbracelet/x/ansi v0.1.4 h1:IEU3D6+dWwPSgZ6HBH+v6oUuZ/nVawMiWj5831KfiLM= +github.com/charmbracelet/x/ansi v0.1.4/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw= +github.com/charmbracelet/x/input v0.1.0 h1:TEsGSfZYQyOtp+STIjyBq6tpRaorH0qpwZUj8DavAhQ= +github.com/charmbracelet/x/input v0.1.0/go.mod h1:ZZwaBxPF7IG8gWWzPUVqHEtWhc1+HXJPNuerJGRGZ28= +github.com/charmbracelet/x/term v0.1.1 h1:3cosVAiPOig+EV4X9U+3LDgtwwAoEzJjNdwbXDjF6yI= +github.com/charmbracelet/x/term v0.1.1/go.mod h1:wB1fHt5ECsu3mXYusyzcngVWWlu1KKUmmLhfgr/Flxw= +github.com/charmbracelet/x/windows v0.1.0 h1:gTaxdvzDM5oMa/I2ZNF7wN78X/atWemG9Wph7Ika2k4= +github.com/charmbracelet/x/windows v0.1.0/go.mod h1:GLEO/l+lizvFDBPLIOk+49gdX49L9YWMB5t+DZd0jkQ= +github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= +github.com/fatih/color v1.17.0 h1:GlRw1BRJxkpqUCBKzKOw098ed57fEsKeNjpTe3cSjK4= +github.com/fatih/color v1.17.0/go.mod h1:YZ7TlrGPkiz6ku9fK3TLD/pl3CpsiFyu8N92HLgmosI= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= +github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= +github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= +github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= +github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo= +github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= +github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E= +golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= +golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go new file mode 100644 index 0000000..b238338 --- /dev/null +++ b/main.go @@ -0,0 +1,7 @@ +package main + +import "htp/cmd" + +func main() { + cmd.Execute() +}