//  Copyright(C) 2021. Huawei Technologies Co.,Ltd.  All rights reserved.

// Package limiter implement a token bucket limiter
package limiter

import (
"context"
"huawei.com/npu-exporter/hwlog"
"huawei.com/npu-exporter/utils"
"math"
"net/http"
"time"
)

const (
kilo = 1000.0
)

type limitHandler struct {
concurrency chan struct{}
httpHandler http.Handler
log bool
}

// ServeHTTP implement http.Handler
func (h *limitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
ctx := context.TODO()
reqID := req.Header.Get(hwlog.ReqID.String())
if reqID != "" {
ctx = context.WithValue(context.Background(), hwlog.ReqID, reqID)
}
id := req.Header.Get(hwlog.UserID.String())
if id != "" {
ctx = context.WithValue(ctx, hwlog.UserID, id)
}
path := req.URL.Path
clientIP := utils.ClientIP(req)
clientUserAgent := req.UserAgent()
select {
case _, ok := <-h.concurrency:
if !ok {
return
}
start := time.Now()
h.httpHandler.ServeHTTP(w, req)
stop := time.Since(start)
latency := int(math.Ceil(float64(stop.Nanoseconds()) / kilo / kilo))
if h.log {
hwlog.RunLog.InfofWithCtx(ctx, "%s %s: %s <%3d> (%dms) |%15s |%s ", req.Proto, req.Method, path,
http.StatusOK, latency, clientIP, clientUserAgent)
}
h.concurrency <- struct{}{}
default:
hwlog.RunLog.WarnfWithCtx(ctx, "Reject Request:%s: %s <%3d> |%15s |%s ", req.Method, path,
http.StatusServiceUnavailable, clientIP, clientUserAgent)
http.Error(w, "503 too busy", http.StatusServiceUnavailable)
}
}

// NewLimitHandler new a bucket-token limiter
func NewLimitHandler(maxConcur, maxConcurrency int, handler http.Handler, printLog bool) http.Handler {
if maxConcur < 1 || maxConcur > maxConcurrency {
hwlog.RunLog.Fatal("maxConcurrency parameter error")
}
h := &limitHandler{
concurrency: make(chan struct{}, maxConcur),
httpHandler: handler,
log: printLog,
}
for i := 0; i < maxConcur; i++ {
h.concurrency <- struct{}{}
}
return h
}

hwlog--limiter.go的更多相关文章

  1. Cannot send session cache limiter Cannot modify header information

    当php报出  Cannot send session cache limiter 或Cannot modify header information   的错误时   其理论上是因为php代码以前有 ...

  2. Warning: session_start() [function.session-start]: Cannot send session cache limiter

    Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers alrea ...

  3. go笔记-限速器(limiter)

    参考: https://blog.csdn.net/wdy_yx/article/details/73849713https://www.jianshu.com/p/1ecb513f7632 http ...

  4. ICD2 VPP limiter for new PIC microcontrollers.

    http://www.circuitsathome.com/mcu/pic_vpp_limiter VOUT = 2.5V * ( 1 + 24/10 ) = 2.5 * 3.4 = 8.5V New ...

  5. rate limiter - system design

    1 问题 Whenever you expose a web service / api endpoint, you need to implement a rate limiter to preve ...

  6. 359. Logger Rate Limiter

    /* * 359. Logger Rate Limiter * 2016-7-14 by Mingyang * 很简单的HashMap,不详谈 */ class Logger { HashMap< ...

  7. Rate Limiter

    Whenever you expose a web service / api endpoint, you need to implement a rate limiter to prevent ab ...

  8. RocksDB Rate Limiter源码解析

    这次的项目我们重点关注RocksDB中的一个环节:Rate Limiter.其实Rate Limiter的思想在很多其他系统中也很常用. 在RocksDB中,后台会实时运行compaction和flu ...

  9. 详解FL Studio压缩器——Fruity Limiter(上)

    压缩,是电音制作中重要一步,将声音信号压缩后可过滤噪音并使音质变好.众所周知,音乐编曲软件FL Studio的特色就是电音制作,所以必不可少要用到压缩器,今天我们就用FL Studio20来讲解一下. ...

  10. 详解FL Studio压缩器——Fruity Limiter(下)

    Hello!小伙伴们又见面啦-接上一篇,本篇咱们继续讲解音乐编曲软件FL Studio20压缩器内容. 包络"ENVELOPE"中包含三个旋钮,它们都有什么作用呢?一起来揭晓吧! ...

随机推荐

  1. Helm安装ingress-nginx-4.2.3

    Application version 1.3.0 Chart version 4.2.3 获取chart包 helm fetch ingress-nginx/ingress-nginx --vers ...

  2. 03 最小CMake项目

    03 最小CMake项目 所有CMake项目都从一个CMakeLists.txt文件开始,此文件应该放在源代码树的最顶层目录下.可以将CMakeLists.txt想象成CMake项目文件,定义了从源和 ...

  3. (数据科学学习手札143)为geopandas添加gdb文件写出功能

    本文示例代码已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 1 简介 大家好我是费老师,很多读者朋友跟随着我先前写作的 ...

  4. Django 测试脚本

    一.测试脚本 Django 在创建项目时自动在应用下创建了tests.py,这个py文件可以作为测试文件:也可以在应用下手动创建一个py测试文件. 无论哪种方式,都需要提前书写以下代码. from d ...

  5. 新版本中的hits.total匹配数说明

    在7.0版发布之前,hits.total始终用于表示符合查询条件的文档的实际数量.在Elasticsearch 7.0版中,如果匹配数大于10,000,则不会计算hits.total. 这是为了避免为 ...

  6. 图解 Kubernetes Service

    文章转载自:https://www.qikqiak.com/post/visually-explained-k8s-service/ 原文链接:https://medium.com/swlh/kube ...

  7. Docker网络详细理解-容器网络互通

    这篇文章主要解决以下几个问题: 1.同一个网段的容器互相之间通过ip进行ping通 2.同一个网段的容器互相之间通过容器名,通过使用--link进行ping通,已放弃这种方法 3.同一个网段的容器互相 ...

  8. useContext 解决函数父子组件传值

    1在父组件外部定义变量A创建上下文,2在父组件使用变量A<A.Provider> <子组件/> </A.Provider> ,3.在子组件中创建变量使用useCon ...

  9. 9_SpringBoot

    一. SpringBoot介绍 1.1. 引言 为了使用SSM框架去开发, 准备SSM框架的模板配置 为了使Spring整合第三方框架, 单独的去编写xml文件 导致SSM项目后期xml文件特别多, ...

  10. v-infinite-scroll无限滚动

    v-infinite-scroll="loadMore"表示回调函数是loadMore infinite-scroll-disabled="busy"表示由变量 ...