Showing posts with label go. Show all posts
Showing posts with label go. Show all posts

Graceful shutdown

 Graceful shutdown of a program involves

  • Sending SIGTERM(notify
    program that its going to be killed) ,upon receiving this signal the program stops receiving further requests(could be web requests, database operations etc)

  • Finalize ongoing/pending tasks(in-flight data)

  • Release resources (file locks, memory) and terminate(with exit status 0)

Process should be robust against sudden death(eg. power failure, hardware failures). Using robust message queue(beanstalkd) is recommended for such scenarios

Queue Concept-

  • producer puts job in the Queue(eg. json, xml)
  • consumer monitors that Queue and takes/reserve the available job
  • consumer deletes the job from Queue

Read disposability

Graceful shutdown example for golang
https://pkg.go.dev/os/signal#Notify

package main

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    // Hello world, the web server
    helloHandler := func(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintf(w, "You requessted %s - %s", req.URL, req.Method)
        fmt.Println("Serving requests from hey...")
        time.Sleep(time.Second * 2)
        defer fmt.Println("remaining")  // acts as remaining requests 
    }
    api := &http.Server{
        Addr:           ":8080",
        Handler:        http.HandlerFunc(helloHandler),
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }

    serverErrors := make(chan error, 1)
    shutdown := make(chan os.Signal, 1)
    go func() {
        log.Printf("main api listening on %s", api.Addr)
        serverErrors <- api.ListenAndServe()
    }()

    signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM)
    //above is not blocking operation although waiting on shutdown channel
    select {
    case err := <-serverErrors:
        log.Fatalf("Error while listening and starting http server: %v", err)

    case <-shutdown:
        log.Println("main: Starting shutdown")
        const timeout = 5 * time.Second
        // Context - it is used for Cancellation and propagation, the context.Background() gives empty context
        ctx, cancel := context.WithTimeout(context.Background(), timeout)
        defer cancel()
        err := api.Shutdown(ctx)
        /*Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down.If the provided context expires before the shutdown is complete, Shutdown returns the context's error, otherwise it returns any error returned from closing the Server's underlying Listener(s).*/
        if err != nil {
            log.Printf("main: Graceful shutdown didnot complete in %v:%v", timeout, err)
            err = api.Close()
            //Close() immediately closes all active net.Listeners and any connections in state StateNew, StateActive, or StateIdle. For a graceful shutdown, use Shutdown.
        }
        if err != nil {
            log.Fatalf("main: could not stop server gracefully Error: %v", err)
        }
    }
}


Image description
additional reading: link1(for context timeouts)

Context in go

Context allow you to send cancellation signal to asynchronous process/ go-routine.

context

Methods provided by context interface:-

Value(key) This method returns the value associated with the specified key.

**Done() **This method returns a channel that can be used to receive a cancelation notification.

Deadline() This method returns the Time that represents the deadline for the request and a bool value that will be false if no deadline has been specified.

Err() This method returns an error that indicates why the Done channel received a signal. The context package defines two variables that can be used to compare the error: Canceled indicates that the request was canceled, and DeadlineExeeded indicates that the deadline passed.

Functions https://pkg.go.dev/context#pkg-functions

  • Background()
  • WithCancel(ctx)
  • WithDeadline(ctx,time)
  • WithTimeout(ctx,duration)
  • WithValue(ctx, key,val)
package main

import (
    "sync"
    "time"
    "fmt"
    "context"
)

func processRequest(ctx context.Context, wg *sync.WaitGroup, count int) {
    total := 0
    for i := 0; i < count; i++ {
        select {
        case <-ctx.Done():
            fmt.Println("Stopping processing - request cancelled")
            goto end
        default:
            fmt.Printf("Processing request: %v \n", total)
            total++
            time.Sleep(time.Millisecond * 250)
        }
    }
    fmt.Println("%v Request processed...", total)
end:
    wg.Done()
}
func main() {
    waitGroup := sync.WaitGroup{}
    waitGroup.Add(1)
    fmt.Println("Request dispatched...")
    ctx, cancel := context.WithCancel(context.Background())

    go processRequest(ctx, &waitGroup, 10)
    time.Sleep(time.Second)
    fmt.Println("Canceling req")
        cancel()
    waitGroup.Wait()

}

---

% go run contxt.go
Request dispatched...
Processing request: 0 
Processing request: 1 
Processing request: 2 
Processing request: 3 
Canceling request
Stopping processing - request cancelled

Flamegraphs part 1

 

As a developer/sysadmin you can create flamegraphs to to create visualizations of system performance data recorded with the perf tool. This perf output shows a stack trace followed by a count, for a total of #N number of samples

git clone the flamegraph scripts:

cd /home/ubuntu
git clone https://github.com/brendangregg/FlameGraph

Sampling a go programme which downloads an linuxmint iso

package main
import (
    "fmt"
    "net/http"
    "io"
    "os"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {
    d1 := []byte("helo world\n")
    for i := 0; i < 10000; i++ {
        resp, err := http.Get("https://mirrors.layeronline.com/linuxmint/stable/21/linuxmint-21-cinnamon-64bit.iso")
        //body, err := io.ReadAll(resp.Body)
        fmt.Println(resp.StatusCode)
        check(err)
        defer resp.Body.Close()
        file, err := os.Create("/tmp/hello.iso")
        size, err := io.Copy(file, resp.Body)
        defer file.Close()
        fmt.Printf("downloaded %s with size %d", file, size)
        err = os.WriteFile("/tmp/check.txt", d1, 0644)
        check(err)
    }
}

compile/build the main.go and run it ./main
Get the process id of main e.g ps aux | grep main

perf record -a -F 99 -g -p 1464 -- sleep 20
Running above command creates a perf.data file

perf script > perf.script //it will by default read perf.data from current working directory and redirects stdout to a file perf.script(ascii file)
This command reads the input file and displays the trace recorded.

Creating flame graph:-

./FlameGraph/stackcollapse-perf.pl perf.script  | ./FlameGraph/flamegraph.pl > flame1006.svg

Download and view flame1006.svg in browser

flamegraph for pid 1464

Here we can observe that io.copybuffer function is using most cpu time (io.copy source)
looking further net.(*netFD).Read is the function call using most cpu time. This net.(*netFD).Read implements func (*IPConn) Read
Conn is a generic stream-oriented network connection.
this function reads data from the connection. This func https://go.dev/src/net/http/transfer.go ¶
we also see ksys_read() is called. This function is responsible for retrieving the struct fd that corresponds with the file descriptor passed in by the user. The struct fd structure contains the struct file_operations structure within it.

Image description
sock_read_iter is fired when receiving a message on a socket
By looking at the graph we can conclude that the cpu usage by main programme is spent mostly on reading data from the connection.