github.com/nsqio/nsq@v1.3.0/nsqadmin/notify.go (about)

     1  package nsqadmin
     2  
     3  import (
     4  	"encoding/base64"
     5  	"net/http"
     6  	"net/url"
     7  	"os"
     8  	"strings"
     9  	"time"
    10  )
    11  
    12  type AdminAction struct {
    13  	Action    string `json:"action"`
    14  	Topic     string `json:"topic"`
    15  	Channel   string `json:"channel,omitempty"`
    16  	Node      string `json:"node,omitempty"`
    17  	Timestamp int64  `json:"timestamp"`
    18  	User      string `json:"user,omitempty"`
    19  	RemoteIP  string `json:"remote_ip"`
    20  	UserAgent string `json:"user_agent"`
    21  	URL       string `json:"url"` // The URL of the HTTP request that triggered this action
    22  	Via       string `json:"via"` // the Hostname of the nsqadmin performing this action
    23  }
    24  
    25  func basicAuthUser(req *http.Request) string {
    26  	s := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
    27  	if len(s) != 2 || s[0] != "Basic" {
    28  		return ""
    29  	}
    30  	b, err := base64.StdEncoding.DecodeString(s[1])
    31  	if err != nil {
    32  		return ""
    33  	}
    34  	pair := strings.SplitN(string(b), ":", 2)
    35  	if len(pair) != 2 {
    36  		return ""
    37  	}
    38  	return pair[0]
    39  }
    40  
    41  func (s *httpServer) notifyAdminAction(action, topic, channel, node string, req *http.Request) {
    42  	if s.nsqadmin.getOpts().NotificationHTTPEndpoint == "" {
    43  		return
    44  	}
    45  	via, _ := os.Hostname()
    46  
    47  	u := url.URL{
    48  		Scheme:   "http",
    49  		Host:     req.Host,
    50  		Path:     req.URL.Path,
    51  		RawQuery: req.URL.RawQuery,
    52  	}
    53  	if req.TLS != nil || req.Header.Get("X-Scheme") == "https" {
    54  		u.Scheme = "https"
    55  	}
    56  
    57  	a := &AdminAction{
    58  		Action:    action,
    59  		Topic:     topic,
    60  		Channel:   channel,
    61  		Node:      node,
    62  		Timestamp: time.Now().Unix(),
    63  		User:      basicAuthUser(req),
    64  		RemoteIP:  req.RemoteAddr,
    65  		UserAgent: req.UserAgent(),
    66  		URL:       u.String(),
    67  		Via:       via,
    68  	}
    69  	// Perform all work in a new goroutine so this never blocks
    70  	go func() { s.nsqadmin.notifications <- a }()
    71  }