Compare commits
41 Commits
b6e187a0a7
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 56cf9ba23c | |||
| 289594716c | |||
| 90faa7d681 | |||
| 2d81202b6c | |||
| e67009522d | |||
| 0392966760 | |||
| c73ffda016 | |||
| 085d0bb740 | |||
| 59fa0cc2ee | |||
| c652c2a311 | |||
| 892392466f | |||
| e6d8cb6c5a | |||
| 54eab23eb2 | |||
| a434b9bf84 | |||
| 2681c7313b | |||
| 626819209f | |||
| 8e691a4174 | |||
| 887a28aef5 | |||
| 4aae3704e7 | |||
| 7e929189e1 | |||
| 962ed0cf71 | |||
| bb3a7fc957 | |||
| d00aaae839 | |||
| 40baa86bd6 | |||
| c24d387761 | |||
| c0ab2afcf4 | |||
| d26b3b9295 | |||
| c449bae5ef | |||
| 1f9eb75e41 | |||
| 77397bd6bc | |||
| 54cb3e818f | |||
| 38a3da271a | |||
| fb3f038506 | |||
| e4e0d49ace | |||
| b801be6aca | |||
| 49f2bd077d | |||
| 3f2ce41c2a | |||
| d74ece6596 | |||
| d77fa2108a | |||
| 219e627539 | |||
| 1885e675b2 |
@ -2,13 +2,12 @@ package metric
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/md5"
|
"crypto/md5"
|
||||||
"encoding/binary"
|
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
|
"runtime"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
@ -16,8 +15,6 @@ import (
|
|||||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||||
)
|
)
|
||||||
|
|
||||||
const metric_value_line_size = 19
|
|
||||||
|
|
||||||
type MetricDescription struct {
|
type MetricDescription struct {
|
||||||
Key string
|
Key string
|
||||||
Type MetricType
|
Type MetricType
|
||||||
@ -29,7 +26,35 @@ type MetricDescription struct {
|
|||||||
type Exporter interface {
|
type Exporter interface {
|
||||||
RegisterMetric(*MetricDescription)
|
RegisterMetric(*MetricDescription)
|
||||||
UpdateMetric(string, float64)
|
UpdateMetric(string, float64)
|
||||||
Shutdown()
|
}
|
||||||
|
|
||||||
|
type MetricPipe struct {
|
||||||
|
pipe *os.File
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mp MetricPipe) Close() {
|
||||||
|
if mp.pipe != nil {
|
||||||
|
mp.pipe.Close()
|
||||||
|
mp.pipe = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mp MetricPipe) writeLine(line string) {
|
||||||
|
mp.pipe.WriteString(line + "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMetricPipe(pipeName string) MetricPipe {
|
||||||
|
switch runtime.GOOS {
|
||||||
|
case "linux":
|
||||||
|
pipeName = "/tmp/" + pipeName
|
||||||
|
case "windows":
|
||||||
|
pipeName = `\\.\pipe\` + pipeName
|
||||||
|
}
|
||||||
|
|
||||||
|
f, _ := os.Open(pipeName)
|
||||||
|
return MetricPipe{
|
||||||
|
pipe: f,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type MetricWriter interface {
|
type MetricWriter interface {
|
||||||
@ -45,13 +70,14 @@ func (mw *metric_empty) Add(int64) {}
|
|||||||
var MetricWriterNil = MetricWriter(&metric_empty{})
|
var MetricWriterNil = MetricWriter(&metric_empty{})
|
||||||
|
|
||||||
type metric_int64 struct {
|
type metric_int64 struct {
|
||||||
|
key string
|
||||||
valptr *int64
|
valptr *int64
|
||||||
buff [metric_value_line_size]byte
|
pipe MetricPipe
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mw *metric_int64) printOut() {
|
func (mw *metric_int64) printOut() {
|
||||||
binary.LittleEndian.PutUint64(mw.buff[9:], math.Float64bits(float64(atomic.LoadInt64(mw.valptr))))
|
loaded := atomic.LoadInt64(mw.valptr)
|
||||||
os.Stdout.Write(mw.buff[:])
|
mw.pipe.writeLine(fmt.Sprintf("%s:%d", mw.key, loaded))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mw *metric_int64) Set(newval int64) {
|
func (mw *metric_int64) Set(newval int64) {
|
||||||
@ -64,11 +90,16 @@ func (mw *metric_int64) Add(inc int64) {
|
|||||||
mw.printOut()
|
mw.printOut()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewMetric(mt MetricType, name string, help string, constLabels map[string]string) (writer MetricWriter) {
|
func NewMetric(pipe MetricPipe, mt MetricType, name string, help string, constLabels map[string]string) (writer MetricWriter) {
|
||||||
if !metricEnabled {
|
if !metricEnabled {
|
||||||
return MetricWriterNil
|
return MetricWriterNil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if constLabels == nil {
|
||||||
|
constLabels = map[string]string{}
|
||||||
|
}
|
||||||
|
|
||||||
|
constLabels["pid"] = fmt.Sprintf("%d", os.Getpid())
|
||||||
var disorder []struct {
|
var disorder []struct {
|
||||||
k string
|
k string
|
||||||
v string
|
v string
|
||||||
@ -101,35 +132,17 @@ func NewMetric(mt MetricType, name string, help string, constLabels map[string]s
|
|||||||
})
|
})
|
||||||
|
|
||||||
impl := &metric_int64{
|
impl := &metric_int64{
|
||||||
|
key: key,
|
||||||
valptr: new(int64),
|
valptr: new(int64),
|
||||||
|
pipe: pipe,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl.buff[0] = METRIC_HEAD_INLINE
|
pipe.writeLine(string(temp))
|
||||||
impl.buff[17] = METRIC_TAIL_INLINE
|
|
||||||
impl.buff[18] = '\n'
|
|
||||||
copy(impl.buff[1:], []byte(key))
|
|
||||||
|
|
||||||
output := append([]byte{METRIC_HEAD_INLINE}, temp...)
|
|
||||||
output = append(output, METRIC_TAIL_INLINE, '\n')
|
|
||||||
os.Stdout.Write(output)
|
|
||||||
|
|
||||||
// writer
|
// writer
|
||||||
|
|
||||||
return impl
|
return impl
|
||||||
}
|
}
|
||||||
|
|
||||||
func ReadMetricValue(line []byte) (string, float64) {
|
|
||||||
if len(line) < 16 {
|
|
||||||
return "", 0
|
|
||||||
}
|
|
||||||
|
|
||||||
key := string(line[0:8])
|
|
||||||
valbits := binary.LittleEndian.Uint64(line[8:])
|
|
||||||
val := math.Float64frombits(valbits)
|
|
||||||
|
|
||||||
return key, val
|
|
||||||
}
|
|
||||||
|
|
||||||
var metricEnabled = false
|
var metricEnabled = false
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
package metric
|
package metric
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"maps"
|
||||||
"math"
|
"math"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
|
|
||||||
@ -34,11 +34,6 @@ func convertValueType(in MetricType) prometheus.ValueType {
|
|||||||
return prometheus.UntypedValue
|
return prometheus.UntypedValue
|
||||||
}
|
}
|
||||||
|
|
||||||
type writeRequest struct {
|
|
||||||
key string
|
|
||||||
val float64
|
|
||||||
}
|
|
||||||
|
|
||||||
type prometheusMetricDesc struct {
|
type prometheusMetricDesc struct {
|
||||||
*prometheus.Desc
|
*prometheus.Desc
|
||||||
valueType prometheus.ValueType
|
valueType prometheus.ValueType
|
||||||
@ -46,116 +41,68 @@ type prometheusMetricDesc struct {
|
|||||||
key string
|
key string
|
||||||
}
|
}
|
||||||
|
|
||||||
type prometheusExporter struct {
|
type PrometheusCollector struct {
|
||||||
writerChan chan *writeRequest
|
|
||||||
registerChan chan *prometheusMetricDesc
|
|
||||||
namespace string
|
namespace string
|
||||||
cancel context.CancelFunc
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pe *prometheusExporter) RegisterMetric(nm *MetricDescription) {
|
|
||||||
pe.registerChan <- &prometheusMetricDesc{
|
|
||||||
Desc: prometheus.NewDesc(prometheus.BuildFQName(pe.namespace, "", nm.Name), nm.Help, nil, nm.ConstLabels),
|
|
||||||
valueType: convertValueType(nm.Type),
|
|
||||||
valptr: new(uint64),
|
|
||||||
key: nm.Key,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pe *prometheusExporter) UpdateMetric(key string, val float64) {
|
|
||||||
pe.writerChan <- &writeRequest{key: key, val: val}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pe *prometheusExporter) Shutdown() {
|
|
||||||
if pe.cancel != nil {
|
|
||||||
pe.cancel()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type prometheusCollector struct {
|
|
||||||
metrics map[string]*prometheusMetricDesc
|
metrics map[string]*prometheusMetricDesc
|
||||||
|
registry *prometheus.Registry
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pc *prometheusCollector) Describe(ch chan<- *prometheus.Desc) {
|
func (pc *PrometheusCollector) Describe(ch chan<- *prometheus.Desc) {
|
||||||
for _, v := range pc.metrics {
|
for _, v := range pc.metrics {
|
||||||
|
logger.Println("collector describe :", v.Desc.String())
|
||||||
ch <- v.Desc
|
ch <- v.Desc
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pc *prometheusCollector) Collect(ch chan<- prometheus.Metric) {
|
func (pc *PrometheusCollector) Collect(ch chan<- prometheus.Metric) {
|
||||||
for _, v := range pc.metrics {
|
for _, v := range pc.metrics {
|
||||||
cm, err := prometheus.NewConstMetric(v.Desc, v.valueType, math.Float64frombits(atomic.LoadUint64(v.valptr)))
|
value := atomic.LoadUint64(v.valptr)
|
||||||
|
cm, err := prometheus.NewConstMetric(v.Desc, v.valueType, math.Float64frombits(value))
|
||||||
if err == nil {
|
if err == nil {
|
||||||
ch <- cm
|
ch <- cm
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pe *prometheusExporter) loop(ctx context.Context) {
|
func (pc *PrometheusCollector) RegisterMetric(md *MetricDescription) *PrometheusCollector {
|
||||||
defer func() {
|
nm := &prometheusMetricDesc{
|
||||||
r := recover()
|
Desc: prometheus.NewDesc(prometheus.BuildFQName("ou", "", md.Name), md.Help, nil, md.ConstLabels),
|
||||||
if r != nil {
|
valueType: convertValueType(md.Type),
|
||||||
logger.Error(r)
|
valptr: new(uint64),
|
||||||
}
|
key: md.Key,
|
||||||
}()
|
|
||||||
|
|
||||||
var collector *prometheusCollector
|
|
||||||
defer func() {
|
|
||||||
if collector != nil {
|
|
||||||
prometheus.Unregister(collector)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return
|
|
||||||
|
|
||||||
case req := <-pe.writerChan:
|
|
||||||
if collector != nil {
|
|
||||||
if m := collector.metrics[req.key]; m != nil {
|
|
||||||
atomic.StoreUint64(m.valptr, math.Float64bits(req.val))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
case nm := <-pe.registerChan:
|
next := NewPrometheusCollector(pc.namespace, pc.registry)
|
||||||
var nextmetrics map[string]*prometheusMetricDesc
|
maps.Copy(next.metrics, pc.metrics)
|
||||||
if collector != nil {
|
next.metrics[nm.key] = nm
|
||||||
nextmetrics = collector.metrics
|
|
||||||
prometheus.Unregister(collector)
|
|
||||||
nextmetrics[nm.key] = nm
|
|
||||||
} else {
|
|
||||||
nextmetrics = map[string]*prometheusMetricDesc{
|
|
||||||
nm.key: nm,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
nextcollector := &prometheusCollector{
|
pc.registry.Unregister(pc)
|
||||||
metrics: nextmetrics,
|
pc.registry.Register(next)
|
||||||
}
|
|
||||||
|
|
||||||
if err := prometheus.Register(nextcollector); err != nil {
|
return next
|
||||||
if _, ok := err.(prometheus.AlreadyRegisteredError); ok {
|
}
|
||||||
// 이미 등록된 metric. child process를 여럿 실행하면 발생됨
|
|
||||||
} else {
|
func (pc *PrometheusCollector) UpdateMetric(key string, val float64) {
|
||||||
logger.Error("prometheus register err :", *nm, err)
|
if m := pc.metrics[key]; m != nil {
|
||||||
}
|
atomic.StoreUint64(m.valptr, math.Float64bits(val))
|
||||||
} else {
|
|
||||||
collector = nextcollector
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPrometheusExport(namespace string) Exporter {
|
func (pc *PrometheusCollector) UnregisterMetric(key string) *PrometheusCollector {
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
next := NewPrometheusCollector(pc.namespace, pc.registry)
|
||||||
exp := &prometheusExporter{
|
maps.Copy(next.metrics, pc.metrics)
|
||||||
registerChan: make(chan *prometheusMetricDesc, 10),
|
delete(next.metrics, key)
|
||||||
writerChan: make(chan *writeRequest, 100),
|
|
||||||
|
pc.registry.Unregister(pc)
|
||||||
|
pc.registry.Register(next)
|
||||||
|
|
||||||
|
return next
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPrometheusCollector(namespace string, registry *prometheus.Registry) *PrometheusCollector {
|
||||||
|
return &PrometheusCollector{
|
||||||
namespace: namespace,
|
namespace: namespace,
|
||||||
cancel: cancel,
|
metrics: make(map[string]*prometheusMetricDesc),
|
||||||
|
registry: registry,
|
||||||
}
|
}
|
||||||
|
|
||||||
go exp.loop(ctx)
|
|
||||||
return exp
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
package opensearch
|
package opensearch
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"context"
|
"context"
|
||||||
"crypto/hmac"
|
"crypto/hmac"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
@ -9,7 +8,9 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@ -18,6 +19,8 @@ import (
|
|||||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const logbulksize = 512 * 1024
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
osg.Config `json:",inline"`
|
osg.Config `json:",inline"`
|
||||||
IndexPrefix string `json:"IndexPrefix"`
|
IndexPrefix string `json:"IndexPrefix"`
|
||||||
@ -31,6 +34,11 @@ type Client struct {
|
|||||||
indexTemplatePattern string
|
indexTemplatePattern string
|
||||||
bulkHeader http.Header
|
bulkHeader http.Header
|
||||||
singleHeader http.Header
|
singleHeader http.Header
|
||||||
|
bulkChan chan *LogDocument
|
||||||
|
singleLogPrepend []byte
|
||||||
|
singleLogMidpend []byte
|
||||||
|
singleLogAppend []byte
|
||||||
|
singleLogFixedSize int
|
||||||
}
|
}
|
||||||
|
|
||||||
type LogDocument struct {
|
type LogDocument struct {
|
||||||
@ -55,58 +63,257 @@ func NewLogDocument(logType string, body any) *LogDocument {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) Send(ld *LogDocument) error {
|
func (c *Client) Send(ld *LogDocument) {
|
||||||
if c.Client == nil {
|
if c.Client == nil {
|
||||||
return nil
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
serialized, _ := json.Marshal(ld)
|
c.bulkChan <- ld
|
||||||
reader := bytes.NewBuffer(serialized)
|
|
||||||
req := osapi.IndexReq{
|
|
||||||
Index: c.indexTemplatePattern + ld.Type,
|
|
||||||
Body: reader,
|
|
||||||
Header: c.singleHeader,
|
|
||||||
}
|
|
||||||
logger.Println("LogSend", req)
|
|
||||||
|
|
||||||
resp, err := c.Do(context.Background(), req, nil)
|
|
||||||
logger.Println(resp)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
r, err2 := io.ReadAll(resp.Body)
|
|
||||||
if err2 != nil {
|
|
||||||
logger.Println("LogSend resp read error :", err2)
|
|
||||||
} else {
|
|
||||||
logger.Println("LogSend resp :", string(r))
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) SendBulk(ds map[string]*LogDocument) error {
|
func (c *Client) SendBulk(ds map[string]*LogDocument) {
|
||||||
var contents string
|
if c == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
for _, d := range ds {
|
for _, d := range ds {
|
||||||
b, _ := json.Marshal(d)
|
c.bulkChan <- d
|
||||||
contents += fmt.Sprintf(`{"create":{"_index":"%s%s"}}`+"\n"+`%s`+"\n", c.indexTemplatePattern, d.Type, string(b))
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type singleLogMarshaller struct {
|
||||||
|
singleLogPrepend []byte
|
||||||
|
singleLogMidpend []byte
|
||||||
|
singleLogAppend []byte
|
||||||
|
|
||||||
|
logtype []byte
|
||||||
|
content []byte
|
||||||
|
length int
|
||||||
|
}
|
||||||
|
|
||||||
|
type logSliceReader struct {
|
||||||
|
src []*singleLogMarshaller
|
||||||
|
cursor int
|
||||||
|
}
|
||||||
|
|
||||||
|
func newLogSliceReader(in []singleLogMarshaller) *logSliceReader {
|
||||||
|
src := make([]*singleLogMarshaller, len(in))
|
||||||
|
for i, v := range in {
|
||||||
|
copylog := new(singleLogMarshaller)
|
||||||
|
*copylog = v
|
||||||
|
src[i] = copylog
|
||||||
}
|
}
|
||||||
|
|
||||||
reader := bytes.NewBuffer([]byte(contents))
|
return &logSliceReader{
|
||||||
|
src: src,
|
||||||
|
cursor: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *logSliceReader) Read(p []byte) (n int, err error) {
|
||||||
|
n = 0
|
||||||
|
err = nil
|
||||||
|
|
||||||
|
advance := func(in []byte) []byte {
|
||||||
|
if len(in) == 0 {
|
||||||
|
return in
|
||||||
|
}
|
||||||
|
|
||||||
|
copied := copy(p, in)
|
||||||
|
p = p[copied:]
|
||||||
|
n += copied
|
||||||
|
return in[copied:]
|
||||||
|
}
|
||||||
|
|
||||||
|
for b.cursor < len(b.src) {
|
||||||
|
sbt := b.src[b.cursor]
|
||||||
|
|
||||||
|
if sbt.singleLogPrepend = advance(sbt.singleLogPrepend); len(sbt.singleLogPrepend) > 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if sbt.logtype = advance(sbt.logtype); len(sbt.logtype) > 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if sbt.singleLogMidpend = advance(sbt.singleLogMidpend); len(sbt.singleLogMidpend) > 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if sbt.content = advance(sbt.content); len(sbt.content) > 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if sbt.singleLogAppend = advance(sbt.singleLogAppend); len(sbt.singleLogAppend) > 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
b.cursor++
|
||||||
|
}
|
||||||
|
|
||||||
|
err = io.EOF
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *logSliceReader) printSent() {
|
||||||
|
for _, r := range b.src {
|
||||||
|
fmt.Print(string(r.content))
|
||||||
|
}
|
||||||
|
fmt.Print("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) sendLoop(ctx context.Context) {
|
||||||
|
defer func() {
|
||||||
|
r := recover()
|
||||||
|
if r != nil {
|
||||||
|
logger.Error(r)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
failChan := make(chan []singleLogMarshaller)
|
||||||
|
var logMarshallers []singleLogMarshaller
|
||||||
|
sendTick := time.After(time.Minute)
|
||||||
|
|
||||||
|
sendfunc := func(logs []singleLogMarshaller) {
|
||||||
|
if len(logs) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
r := recover()
|
||||||
|
if r != nil {
|
||||||
|
logger.Println(r)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
reader := newLogSliceReader(logs)
|
||||||
req := osapi.BulkReq{
|
req := osapi.BulkReq{
|
||||||
Body: reader,
|
Body: reader,
|
||||||
Header: c.bulkHeader,
|
Header: c.bulkHeader,
|
||||||
}
|
}
|
||||||
resp, err := c.Do(context.Background(), req, nil)
|
resp, err := c.Do(context.Background(), req, nil)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
if netoperr, ok := err.(*net.OpError); ok && netoperr.Op == "dial" {
|
||||||
|
// 접속 안됨. 재시도 안함
|
||||||
|
logger.Println("[LogStream] send bulk failed. no retry :", err)
|
||||||
|
reader.printSent()
|
||||||
|
} else {
|
||||||
|
// 재시도
|
||||||
|
logger.Println("[LogStream] send bulk failed. retry :", err)
|
||||||
|
failChan <- logs
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if resp.Body == nil {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
logger.Println(resp)
|
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
return nil
|
var respbody struct {
|
||||||
|
Errors bool `json:"errors"`
|
||||||
|
Items []struct {
|
||||||
|
Create struct {
|
||||||
|
Status int `json:"status"`
|
||||||
|
} `json:"create"`
|
||||||
|
} `json:"items"`
|
||||||
|
}
|
||||||
|
|
||||||
|
decoder := json.NewDecoder(resp.Body)
|
||||||
|
if err := decoder.Decode(&respbody); err != nil {
|
||||||
|
errbody, _ := io.ReadAll(decoder.Buffered())
|
||||||
|
logger.Println("[LogStream] decode response body failed and retry :", err, string(errbody), len(logs))
|
||||||
|
// 전체 재시도 필요
|
||||||
|
failChan <- logs
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !respbody.Errors {
|
||||||
|
// 성공
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var retry []singleLogMarshaller
|
||||||
|
for i, item := range respbody.Items {
|
||||||
|
if item.Create.Status < 300 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if item.Create.Status == 429 || item.Create.Status >= 500 {
|
||||||
|
logger.Println("[LogStream] send bulk failed but retry. status :", item.Create.Status)
|
||||||
|
retry = append(retry, logs[i])
|
||||||
|
} else if item.Create.Status == 400 {
|
||||||
|
// 구문 오류. 재시도 불가
|
||||||
|
if i < len(logs) {
|
||||||
|
logger.Println("[LogStream] send bulk failed. status 400 :", string(logs[i].content))
|
||||||
|
} else {
|
||||||
|
logger.Println("[LogStream] send bulk failed. status 400 but out of index :", i, len(logs))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 일단 로그만
|
||||||
|
logger.Println("[LogStream] send bulk failed but no retry. status :", item.Create.Status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(retry) > 0 {
|
||||||
|
failChan <- retry
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
totalsize := 0
|
||||||
|
appendLog := func(newlog singleLogMarshaller) bool {
|
||||||
|
if totalsize+newlog.length > logbulksize {
|
||||||
|
go sendfunc(logMarshallers)
|
||||||
|
totalsize = newlog.length
|
||||||
|
logMarshallers = []singleLogMarshaller{newlog}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
totalsize += newlog.length
|
||||||
|
logMarshallers = append(logMarshallers, newlog)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
|
||||||
|
case ret := <-failChan:
|
||||||
|
// 순서는 중요하지 않음.
|
||||||
|
sent := false
|
||||||
|
for _, newlog := range ret {
|
||||||
|
sent = sent || appendLog(newlog)
|
||||||
|
}
|
||||||
|
|
||||||
|
if sent {
|
||||||
|
sendTick = time.After(time.Minute)
|
||||||
|
}
|
||||||
|
|
||||||
|
case <-sendTick:
|
||||||
|
if len(logMarshallers) > 0 {
|
||||||
|
go sendfunc(logMarshallers)
|
||||||
|
totalsize = 0
|
||||||
|
logMarshallers = nil
|
||||||
|
} else {
|
||||||
|
sendTick = time.After(time.Minute)
|
||||||
|
}
|
||||||
|
|
||||||
|
case logDoc := <-c.bulkChan:
|
||||||
|
b, _ := json.Marshal(logDoc)
|
||||||
|
logtype := []byte(logDoc.Type)
|
||||||
|
|
||||||
|
if appendLog(singleLogMarshaller{
|
||||||
|
singleLogPrepend: c.singleLogPrepend,
|
||||||
|
singleLogMidpend: c.singleLogMidpend,
|
||||||
|
singleLogAppend: c.singleLogAppend,
|
||||||
|
logtype: logtype,
|
||||||
|
content: b,
|
||||||
|
length: len(logtype) + len(b) + c.singleLogFixedSize,
|
||||||
|
}) {
|
||||||
|
sendTick = time.After(time.Minute)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var jwtHeader string
|
var jwtHeader string
|
||||||
@ -120,13 +327,13 @@ func init() {
|
|||||||
jwtHeader = string(dst[:enclen])
|
jwtHeader = string(dst[:enclen])
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) MakeJWT(subject string, ttl time.Duration) string {
|
func (c *Client) MakeJWT(subject string, role string, ttl time.Duration) string {
|
||||||
if len(c.signingKey) == 0 {
|
if len(c.signingKey) == 0 {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
now := time.Now().UTC().Add(ttl).Add(time.Hour).Unix()
|
now := time.Now().Add(ttl).Unix()
|
||||||
src := []byte(fmt.Sprintf(`{"exp":%d,"sub":"%s","roles":"ds_client_full_access"}`, now, subject))
|
src := fmt.Appendf(nil, `{"exp":%d,"sub":"%s","roles":"%s"}`, now, subject, role)
|
||||||
payload := make([]byte, encoding.EncodedLen(len(src)))
|
payload := make([]byte, encoding.EncodedLen(len(src)))
|
||||||
encoding.Encode(payload, src)
|
encoding.Encode(payload, src)
|
||||||
|
|
||||||
@ -140,11 +347,56 @@ func (c *Client) MakeJWT(subject string, ttl time.Duration) string {
|
|||||||
return encoded + "." + string(sigenc)
|
return encoded + "." + string(sigenc)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewClient(cfg Config) (Client, error) {
|
func (c *Client) VerifyJWT(token string) (subject string, role string) {
|
||||||
|
dot := strings.LastIndex(token, ".")
|
||||||
|
if dot < 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
encoded := token[:dot]
|
||||||
|
sigenc := token[dot+1:]
|
||||||
|
signature := make([]byte, encoding.DecodedLen(len(sigenc)))
|
||||||
|
encoding.Decode(signature, []byte(sigenc))
|
||||||
|
|
||||||
|
mac := hmac.New(sha256.New, c.signingKey)
|
||||||
|
mac.Write([]byte(encoded))
|
||||||
|
calsig := mac.Sum(nil)
|
||||||
|
if slices.Compare(calsig, signature) != 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_, payload, ok := strings.Cut(encoded, ".")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
srcjson, err := encoding.DecodeString(payload)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var src struct {
|
||||||
|
Exp int64 `json:"exp"`
|
||||||
|
Sub string `json:"sub"`
|
||||||
|
Roles string `json:"roles"`
|
||||||
|
}
|
||||||
|
if json.Unmarshal([]byte(srcjson), &src) != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if src.Exp < time.Now().Unix() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
return src.Sub, src.Roles
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewClient(ctx context.Context, cfg Config) (Client, error) {
|
||||||
if len(cfg.Addresses) == 0 {
|
if len(cfg.Addresses) == 0 {
|
||||||
return Client{}, nil
|
return Client{}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// retry는 수동으로
|
||||||
|
cfg.Config.DisableRetry = true
|
||||||
client, err := osg.NewClient(cfg.Config)
|
client, err := osg.NewClient(cfg.Config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Client{}, err
|
return Client{}, err
|
||||||
@ -158,27 +410,49 @@ func NewClient(cfg Config) (Client, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
indexPrefix := cfg.IndexPrefix
|
indexPrefix := cfg.IndexPrefix
|
||||||
if !strings.HasSuffix(indexPrefix, "-") {
|
if !strings.HasSuffix(indexPrefix, "-") && len(indexPrefix) > 0 {
|
||||||
indexPrefix += "-"
|
indexPrefix += "-"
|
||||||
}
|
}
|
||||||
if !strings.HasSuffix(indexPrefix, "ds-logs-") {
|
if !strings.HasSuffix(indexPrefix, "ds-logs-") {
|
||||||
indexPrefix = "ds-logs-" + indexPrefix
|
indexPrefix = "ds-logs-" + indexPrefix
|
||||||
}
|
}
|
||||||
|
|
||||||
authHeader := fmt.Sprintf("Basic %s", base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", cfg.Username, cfg.Password))))
|
logger.Println("[LogStream] stream indexPrefix :", indexPrefix)
|
||||||
|
|
||||||
bulkHeader := make(http.Header)
|
bulkHeader := make(http.Header)
|
||||||
bulkHeader.Set("Authorization", authHeader)
|
|
||||||
|
|
||||||
singleHeader := make(http.Header)
|
singleHeader := make(http.Header)
|
||||||
|
if len(cfg.Username) > 0 && len(cfg.Password) > 0 {
|
||||||
|
authHeader := fmt.Sprintf("Basic %s", base64.RawURLEncoding.EncodeToString(fmt.Appendf(nil, "%s:%s", cfg.Username, cfg.Password)))
|
||||||
|
bulkHeader.Set("Authorization", authHeader)
|
||||||
singleHeader.Set("Authorization", authHeader)
|
singleHeader.Set("Authorization", authHeader)
|
||||||
|
}
|
||||||
|
|
||||||
return Client{
|
singleLogPrepend := fmt.Appendf(nil, `{"create":{"_index":"%s`, indexPrefix)
|
||||||
|
singleLogMidpend := []byte("\"}}\n")
|
||||||
|
singleLogAppend := []byte("\n")
|
||||||
|
singleLogFixedSize := len(singleLogPrepend) + len(singleLogMidpend) + len(singleLogAppend)
|
||||||
|
|
||||||
|
out := Client{
|
||||||
Client: client,
|
Client: client,
|
||||||
cfg: cfg,
|
cfg: cfg,
|
||||||
signingKey: signingKey,
|
signingKey: signingKey,
|
||||||
indexTemplatePattern: indexPrefix,
|
indexTemplatePattern: indexPrefix,
|
||||||
bulkHeader: bulkHeader,
|
bulkHeader: bulkHeader,
|
||||||
singleHeader: singleHeader,
|
singleHeader: singleHeader,
|
||||||
}, nil
|
bulkChan: make(chan *LogDocument, 1000),
|
||||||
|
|
||||||
|
singleLogPrepend: singleLogPrepend,
|
||||||
|
singleLogMidpend: singleLogMidpend,
|
||||||
|
singleLogAppend: singleLogAppend,
|
||||||
|
singleLogFixedSize: singleLogFixedSize,
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
out.sendLoop(ctx)
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,11 @@
|
|||||||
package opensearch
|
package opensearch
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/base64"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestNewClient(t *testing.T) {
|
func TestNewClient(t *testing.T) {
|
||||||
@ -31,3 +35,44 @@ func TestNewClient(t *testing.T) {
|
|||||||
// time.Sleep(time.Second)
|
// time.Sleep(time.Second)
|
||||||
// }
|
// }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestClient_MakeJWT(t *testing.T) {
|
||||||
|
sk := "UGdiOTdLVjFBTWtndTRNRiZmVjdwMDdCRW1lSSUxTnA="
|
||||||
|
dst := make([]byte, len(sk)*2)
|
||||||
|
dstlen, _ := base64.StdEncoding.Decode(dst, []byte(sk))
|
||||||
|
signingKey := dst[:dstlen]
|
||||||
|
uid := primitive.NewObjectID().Hex()
|
||||||
|
|
||||||
|
type args struct {
|
||||||
|
subject string
|
||||||
|
role string
|
||||||
|
ttl time.Duration
|
||||||
|
}
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
c *Client
|
||||||
|
args args
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
// TODO: Add test cases.
|
||||||
|
{
|
||||||
|
c: &Client{
|
||||||
|
signingKey: signingKey,
|
||||||
|
},
|
||||||
|
args: args{
|
||||||
|
subject: uid,
|
||||||
|
role: "ds_client",
|
||||||
|
ttl: time.Minute,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got := tt.c.MakeJWT(tt.args.subject, tt.args.role, tt.args.ttl)
|
||||||
|
subj, role := tt.c.VerifyJWT(got)
|
||||||
|
if subj != tt.args.subject || role != tt.args.role {
|
||||||
|
t.Errorf("Client.MakeJWT() = %v, %v, want %v, %v", subj, role, tt.args.subject, tt.args.role)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -116,7 +116,13 @@ func LoadConfig[T any](outptr *T) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return json.Unmarshal([]byte(os.ExpandEnv(string(configContents))), outptr)
|
return json.Unmarshal([]byte(os.Expand(string(configContents), func(in string) string {
|
||||||
|
envval := os.Getenv(in)
|
||||||
|
if len(envval) == 0 {
|
||||||
|
return "$" + in
|
||||||
|
}
|
||||||
|
return envval
|
||||||
|
})), outptr)
|
||||||
}
|
}
|
||||||
|
|
||||||
type StorageAddr struct {
|
type StorageAddr struct {
|
||||||
|
|||||||
13
server.go
13
server.go
@ -352,8 +352,19 @@ func ConvertInterface(from interface{}, toType reflect.Type) reflect.Value {
|
|||||||
return convslice
|
return convslice
|
||||||
|
|
||||||
case reflect.Bool:
|
case reflect.Bool:
|
||||||
val, _ := strconv.ParseBool(from.(string))
|
if fromstr, ok := from.(string); ok {
|
||||||
|
val, _ := strconv.ParseBool(fromstr)
|
||||||
return reflect.ValueOf(val)
|
return reflect.ValueOf(val)
|
||||||
|
} else if frombool, ok := from.(bool); ok {
|
||||||
|
return reflect.ValueOf(frombool)
|
||||||
|
}
|
||||||
|
return reflect.ValueOf(false)
|
||||||
|
|
||||||
|
case reflect.String:
|
||||||
|
if toType == reflect.TypeOf(primitive.ObjectID{}) {
|
||||||
|
objid, _ := primitive.ObjectIDFromHex(from.(string))
|
||||||
|
return reflect.ValueOf(objid)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return fromrv.Convert(toType)
|
return fromrv.Convert(toType)
|
||||||
|
|||||||
@ -6,6 +6,7 @@ import (
|
|||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@ -14,12 +15,12 @@ import (
|
|||||||
|
|
||||||
type Authorization struct {
|
type Authorization struct {
|
||||||
Account primitive.ObjectID `bson:"a" json:"a"`
|
Account primitive.ObjectID `bson:"a" json:"a"`
|
||||||
invalidated string
|
|
||||||
|
|
||||||
// by authorization provider
|
// by authorization provider
|
||||||
Platform string `bson:"p" json:"p"`
|
Platform string `bson:"p" json:"p"`
|
||||||
Uid string `bson:"u" json:"u"`
|
Uid string `bson:"u" json:"u"`
|
||||||
Alias string `bson:"al" json:"al"`
|
Alias string `bson:"al" json:"al"`
|
||||||
|
CreatedTime int64 `bson:"ct" json:"ct"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (auth *Authorization) ToStrings() []string {
|
func (auth *Authorization) ToStrings() []string {
|
||||||
@ -28,38 +29,45 @@ func (auth *Authorization) ToStrings() []string {
|
|||||||
"p", auth.Platform,
|
"p", auth.Platform,
|
||||||
"u", auth.Uid,
|
"u", auth.Uid,
|
||||||
"al", auth.Alias,
|
"al", auth.Alias,
|
||||||
"inv", auth.invalidated,
|
"ct", strconv.FormatInt(auth.CreatedTime, 10),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (auth *Authorization) Invalidated() bool {
|
func (auth *Authorization) Valid() bool {
|
||||||
return len(auth.invalidated) > 0
|
return !auth.Account.IsZero()
|
||||||
}
|
}
|
||||||
|
|
||||||
func MakeAuthrizationFromStringMap(src map[string]string) Authorization {
|
func MakeAuthrizationFromStringMap(src map[string]string) Authorization {
|
||||||
accid, _ := primitive.ObjectIDFromHex(src["a"])
|
accid, _ := primitive.ObjectIDFromHex(src["a"])
|
||||||
|
ct, _ := strconv.ParseInt(src["ct"], 10, 0)
|
||||||
return Authorization{
|
return Authorization{
|
||||||
Account: accid,
|
Account: accid,
|
||||||
Platform: src["p"],
|
Platform: src["p"],
|
||||||
Uid: src["u"],
|
Uid: src["u"],
|
||||||
Alias: src["al"],
|
Alias: src["al"],
|
||||||
invalidated: src["inv"],
|
CreatedTime: ct,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type Provider interface {
|
type Provider interface {
|
||||||
New(*Authorization) (string, error)
|
New(*Authorization) (string, error)
|
||||||
RevokeAll(primitive.ObjectID) error
|
RevokeAll(primitive.ObjectID, bool) ([]string, error)
|
||||||
Query(string) (Authorization, error)
|
Query(string) (Authorization, error)
|
||||||
Touch(string) (bool, error)
|
Touch(string) (bool, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type InvalidatedSession struct {
|
||||||
|
Account primitive.ObjectID
|
||||||
|
SessionKeys []string
|
||||||
|
Infinite bool
|
||||||
|
}
|
||||||
|
|
||||||
type Consumer interface {
|
type Consumer interface {
|
||||||
Query(string) (Authorization, error)
|
Query(string) Authorization
|
||||||
Touch(string) (Authorization, error)
|
Touch(string) (Authorization, error)
|
||||||
IsRevoked(primitive.ObjectID) bool
|
IsRevoked(primitive.ObjectID) bool
|
||||||
Revoke(string)
|
Revoke(string)
|
||||||
RegisterOnSessionInvalidated(func(primitive.ObjectID))
|
RegisterOnSessionInvalidated(func(InvalidatedSession))
|
||||||
}
|
}
|
||||||
|
|
||||||
type storagekey string
|
type storagekey string
|
||||||
@ -74,10 +82,6 @@ func make_storagekey(acc primitive.ObjectID) storagekey {
|
|||||||
return storagekey(acc.Hex() + hex.EncodeToString(bs[2:]))
|
return storagekey(acc.Hex() + hex.EncodeToString(bs[2:]))
|
||||||
}
|
}
|
||||||
|
|
||||||
func AccountToSessionKey(acc primitive.ObjectID) string {
|
|
||||||
return string(make_storagekey(acc))
|
|
||||||
}
|
|
||||||
|
|
||||||
func storagekey_to_publickey(sk storagekey) publickey {
|
func storagekey_to_publickey(sk storagekey) publickey {
|
||||||
bs, _ := hex.DecodeString(string(sk))
|
bs, _ := hex.DecodeString(string(sk))
|
||||||
|
|
||||||
@ -119,10 +123,6 @@ var errInvalidScheme = errors.New("storageAddr is not valid scheme")
|
|||||||
var errSessionStorageMissing = errors.New("session_storageis missing")
|
var errSessionStorageMissing = errors.New("session_storageis missing")
|
||||||
|
|
||||||
func NewConsumer(ctx context.Context, storageAddr string, ttl time.Duration) (Consumer, error) {
|
func NewConsumer(ctx context.Context, storageAddr string, ttl time.Duration) (Consumer, error) {
|
||||||
if strings.HasPrefix(storageAddr, "mongodb") {
|
|
||||||
return newConsumerWithMongo(ctx, storageAddr, ttl)
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.HasPrefix(storageAddr, "redis") {
|
if strings.HasPrefix(storageAddr, "redis") {
|
||||||
return newConsumerWithRedis(ctx, storageAddr, ttl)
|
return newConsumerWithRedis(ctx, storageAddr, ttl)
|
||||||
}
|
}
|
||||||
@ -142,10 +142,6 @@ func NewConsumerWithConfig(ctx context.Context, cfg SessionConfig) (Consumer, er
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewProvider(ctx context.Context, storageAddr string, ttl time.Duration) (Provider, error) {
|
func NewProvider(ctx context.Context, storageAddr string, ttl time.Duration) (Provider, error) {
|
||||||
if strings.HasPrefix(storageAddr, "mongodb") {
|
|
||||||
return newProviderWithMongo(ctx, storageAddr, ttl)
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.HasPrefix(storageAddr, "redis") {
|
if strings.HasPrefix(storageAddr, "redis") {
|
||||||
return newProviderWithRedis(ctx, storageAddr, ttl)
|
return newProviderWithRedis(ctx, storageAddr, ttl)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -4,8 +4,6 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type cache_stage[T any] struct {
|
type cache_stage[T any] struct {
|
||||||
@ -26,7 +24,7 @@ type consumer_common[T any] struct {
|
|||||||
ctx context.Context
|
ctx context.Context
|
||||||
stages [2]*cache_stage[T]
|
stages [2]*cache_stage[T]
|
||||||
startTime time.Time
|
startTime time.Time
|
||||||
onSessionInvalidated []func(primitive.ObjectID)
|
onSessionInvalidated []func(InvalidatedSession)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *consumer_common[T]) add_internal(sk storagekey, si T) {
|
func (c *consumer_common[T]) add_internal(sk storagekey, si T) {
|
||||||
|
|||||||
@ -1,383 +0,0 @@
|
|||||||
package session
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"go.mongodb.org/mongo-driver/bson"
|
|
||||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
|
||||||
"go.mongodb.org/mongo-driver/mongo"
|
|
||||||
"go.mongodb.org/mongo-driver/mongo/options"
|
|
||||||
"repositories.action2quare.com/ayo/gocommon"
|
|
||||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
session_collection_name = gocommon.CollectionName("session")
|
|
||||||
)
|
|
||||||
|
|
||||||
type provider_mongo struct {
|
|
||||||
mongoClient gocommon.MongoClient
|
|
||||||
}
|
|
||||||
|
|
||||||
type sessionMongo struct {
|
|
||||||
Id primitive.ObjectID `bson:"_id,omitempty"`
|
|
||||||
Auth *Authorization `bson:"auth"`
|
|
||||||
Key storagekey `bson:"key"`
|
|
||||||
Ts primitive.DateTime `bson:"_ts"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func newProviderWithMongo(ctx context.Context, mongoUrl string, ttl time.Duration) (Provider, error) {
|
|
||||||
mc, err := gocommon.NewMongoClient(ctx, mongoUrl)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = mc.MakeUniqueIndices(session_collection_name, map[string]bson.D{
|
|
||||||
"key": {{Key: "key", Value: 1}},
|
|
||||||
}); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := mc.MakeExpireIndex(session_collection_name, int32(ttl.Seconds())); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return &provider_mongo{
|
|
||||||
mongoClient: mc,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *provider_mongo) New(input *Authorization) (string, error) {
|
|
||||||
sk := make_storagekey(input.Account)
|
|
||||||
|
|
||||||
_, _, err := p.mongoClient.Update(session_collection_name, bson.M{
|
|
||||||
"_id": input.Account,
|
|
||||||
}, bson.M{
|
|
||||||
"$set": sessionMongo{
|
|
||||||
Auth: input,
|
|
||||||
Key: sk,
|
|
||||||
Ts: primitive.NewDateTimeFromTime(time.Now().UTC()),
|
|
||||||
},
|
|
||||||
}, options.Update().SetUpsert(true))
|
|
||||||
|
|
||||||
return string(storagekey_to_publickey(sk)), err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *provider_mongo) RevokeAll(acc primitive.ObjectID) error {
|
|
||||||
_, err := p.mongoClient.Delete(session_collection_name, bson.M{
|
|
||||||
"_id": acc,
|
|
||||||
})
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *provider_mongo) Query(pk string) (Authorization, error) {
|
|
||||||
sk := publickey_to_storagekey(publickey(pk))
|
|
||||||
var auth Authorization
|
|
||||||
err := p.mongoClient.FindOneAs(session_collection_name, bson.M{
|
|
||||||
"key": sk,
|
|
||||||
}, &auth)
|
|
||||||
|
|
||||||
return auth, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *provider_mongo) Touch(pk string) (bool, error) {
|
|
||||||
sk := publickey_to_storagekey(publickey(pk))
|
|
||||||
worked, _, err := p.mongoClient.Update(session_collection_name, bson.M{
|
|
||||||
"key": sk,
|
|
||||||
}, bson.M{
|
|
||||||
"$currentDate": bson.M{
|
|
||||||
"_ts": bson.M{"$type": "date"},
|
|
||||||
},
|
|
||||||
}, options.Update().SetUpsert(false))
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
logger.Println("provider Touch :", err)
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return worked, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type consumer_mongo struct {
|
|
||||||
consumer_common[*sessionMongo]
|
|
||||||
ids map[primitive.ObjectID]storagekey
|
|
||||||
mongoClient gocommon.MongoClient
|
|
||||||
ttl time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
type sessionPipelineDocument struct {
|
|
||||||
OperationType string `bson:"operationType"`
|
|
||||||
DocumentKey struct {
|
|
||||||
Id primitive.ObjectID `bson:"_id"`
|
|
||||||
} `bson:"documentKey"`
|
|
||||||
Session *sessionMongo `bson:"fullDocument"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func newConsumerWithMongo(ctx context.Context, mongoUrl string, ttl time.Duration) (Consumer, error) {
|
|
||||||
mc, err := gocommon.NewMongoClient(ctx, mongoUrl)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
consumer := &consumer_mongo{
|
|
||||||
consumer_common: consumer_common[*sessionMongo]{
|
|
||||||
ttl: ttl,
|
|
||||||
ctx: ctx,
|
|
||||||
stages: [2]*cache_stage[*sessionMongo]{make_cache_stage[*sessionMongo](), make_cache_stage[*sessionMongo]()},
|
|
||||||
startTime: time.Now(),
|
|
||||||
},
|
|
||||||
ids: make(map[primitive.ObjectID]storagekey),
|
|
||||||
ttl: ttl,
|
|
||||||
mongoClient: mc,
|
|
||||||
}
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
matchStage := bson.D{
|
|
||||||
{
|
|
||||||
Key: "$match", Value: bson.D{
|
|
||||||
{Key: "operationType", Value: bson.D{
|
|
||||||
{Key: "$in", Value: bson.A{
|
|
||||||
"delete",
|
|
||||||
"insert",
|
|
||||||
"update",
|
|
||||||
}},
|
|
||||||
}},
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
projectStage := bson.D{
|
|
||||||
{
|
|
||||||
Key: "$project", Value: bson.D{
|
|
||||||
{Key: "documentKey", Value: 1},
|
|
||||||
{Key: "operationType", Value: 1},
|
|
||||||
{Key: "fullDocument", Value: 1},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
var stream *mongo.ChangeStream
|
|
||||||
nextswitch := time.Now().Add(ttl)
|
|
||||||
for {
|
|
||||||
if stream == nil {
|
|
||||||
stream, err = mc.Watch(session_collection_name, mongo.Pipeline{matchStage, projectStage})
|
|
||||||
if err != nil {
|
|
||||||
logger.Error("watchAuthCollection watch failed :", err)
|
|
||||||
time.Sleep(time.Minute)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
changed := stream.TryNext(ctx)
|
|
||||||
if ctx.Err() != nil {
|
|
||||||
logger.Error("watchAuthCollection stream.TryNext failed. process should be restarted! :", ctx.Err().Error())
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
if changed {
|
|
||||||
var data sessionPipelineDocument
|
|
||||||
if err := stream.Decode(&data); err == nil {
|
|
||||||
ot := data.OperationType
|
|
||||||
switch ot {
|
|
||||||
case "insert":
|
|
||||||
consumer.add(data.Session.Key, data.DocumentKey.Id, data.Session)
|
|
||||||
case "update":
|
|
||||||
if data.Session == nil {
|
|
||||||
if old := consumer.deleteById(data.DocumentKey.Id); old != nil {
|
|
||||||
for _, f := range consumer.onSessionInvalidated {
|
|
||||||
f(old.Auth.Account)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
consumer.add(data.Session.Key, data.DocumentKey.Id, data.Session)
|
|
||||||
}
|
|
||||||
case "delete":
|
|
||||||
if old := consumer.deleteById(data.DocumentKey.Id); old != nil {
|
|
||||||
for _, f := range consumer.onSessionInvalidated {
|
|
||||||
f(old.Auth.Account)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
logger.Error("watchAuthCollection stream.Decode failed :", err)
|
|
||||||
}
|
|
||||||
} else if stream.Err() != nil || stream.ID() == 0 {
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
logger.Println("watchAuthCollection is done")
|
|
||||||
stream.Close(ctx)
|
|
||||||
return
|
|
||||||
|
|
||||||
case <-time.After(time.Second):
|
|
||||||
logger.Error("watchAuthCollection stream error :", stream.Err())
|
|
||||||
stream.Close(ctx)
|
|
||||||
stream = nil
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
time.Sleep(time.Second)
|
|
||||||
}
|
|
||||||
|
|
||||||
now := time.Now()
|
|
||||||
for now.After(nextswitch) {
|
|
||||||
consumer.changeStage()
|
|
||||||
nextswitch = nextswitch.Add(ttl)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return consumer, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *consumer_mongo) query_internal(sk storagekey) (*sessionMongo, bool, error) {
|
|
||||||
if _, deleted := c.stages[0].deleted[sk]; deleted {
|
|
||||||
return nil, false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, deleted := c.stages[1].deleted[sk]; deleted {
|
|
||||||
return nil, false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
found, ok := c.stages[0].cache[sk]
|
|
||||||
if !ok {
|
|
||||||
found, ok = c.stages[1].cache[sk]
|
|
||||||
}
|
|
||||||
|
|
||||||
if ok {
|
|
||||||
return found, false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var si sessionMongo
|
|
||||||
err := c.mongoClient.FindOneAs(session_collection_name, bson.M{
|
|
||||||
"key": sk,
|
|
||||||
}, &si)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
logger.Println("consumer Query :", err)
|
|
||||||
return nil, false, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(si.Key) > 0 {
|
|
||||||
siptr := &si
|
|
||||||
c.add_internal(sk, siptr)
|
|
||||||
return siptr, true, nil
|
|
||||||
}
|
|
||||||
return nil, false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *consumer_mongo) Query(pk string) (Authorization, error) {
|
|
||||||
c.lock.Lock()
|
|
||||||
defer c.lock.Unlock()
|
|
||||||
|
|
||||||
sk := publickey_to_storagekey(publickey(pk))
|
|
||||||
si, _, err := c.query_internal(sk)
|
|
||||||
if err != nil {
|
|
||||||
return Authorization{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if si == nil {
|
|
||||||
return Authorization{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if time.Now().After(si.Ts.Time().Add(c.ttl)) {
|
|
||||||
return Authorization{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return *si.Auth, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *consumer_mongo) Touch(pk string) (Authorization, error) {
|
|
||||||
c.lock.Lock()
|
|
||||||
defer c.lock.Unlock()
|
|
||||||
|
|
||||||
sk := publickey_to_storagekey(publickey(pk))
|
|
||||||
worked, _, err := c.mongoClient.Update(session_collection_name, bson.M{
|
|
||||||
"key": sk,
|
|
||||||
}, bson.M{
|
|
||||||
"$currentDate": bson.M{
|
|
||||||
"_ts": bson.M{"$type": "date"},
|
|
||||||
},
|
|
||||||
}, options.Update().SetUpsert(false))
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
logger.Println("consumer Touch :", err)
|
|
||||||
return Authorization{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if !worked {
|
|
||||||
// 이미 만료되서 사라짐
|
|
||||||
return Authorization{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
si, added, err := c.query_internal(sk)
|
|
||||||
if err != nil {
|
|
||||||
return Authorization{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if si == nil {
|
|
||||||
return Authorization{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if !added {
|
|
||||||
var doc sessionMongo
|
|
||||||
err := c.mongoClient.FindOneAs(session_collection_name, bson.M{
|
|
||||||
"key": sk,
|
|
||||||
}, &doc)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
logger.Println("consumer Query :", err)
|
|
||||||
return Authorization{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(si.Key) > 0 {
|
|
||||||
c.add_internal(sk, &doc)
|
|
||||||
c.ids[doc.Id] = sk
|
|
||||||
|
|
||||||
return *doc.Auth, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return *si.Auth, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *consumer_mongo) Revoke(pk string) {
|
|
||||||
sk := publickey_to_storagekey(publickey(pk))
|
|
||||||
_, err := c.mongoClient.Delete(session_collection_name, bson.M{
|
|
||||||
"key": sk,
|
|
||||||
})
|
|
||||||
|
|
||||||
if err == nil {
|
|
||||||
for id, v := range c.ids {
|
|
||||||
if v == sk {
|
|
||||||
delete(c.ids, id)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *consumer_mongo) IsRevoked(id primitive.ObjectID) bool {
|
|
||||||
_, ok := c.ids[id]
|
|
||||||
return !ok
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *consumer_mongo) add(sk storagekey, id primitive.ObjectID, si *sessionMongo) {
|
|
||||||
c.lock.Lock()
|
|
||||||
defer c.lock.Unlock()
|
|
||||||
|
|
||||||
c.consumer_common.add_internal(sk, si)
|
|
||||||
c.ids[id] = sk
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *consumer_mongo) deleteById(id primitive.ObjectID) (old *sessionMongo) {
|
|
||||||
c.lock.Lock()
|
|
||||||
defer c.lock.Unlock()
|
|
||||||
|
|
||||||
if sk, ok := c.ids[id]; ok {
|
|
||||||
old = c.consumer_common.delete_internal(sk)
|
|
||||||
delete(c.ids, id)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *consumer_mongo) RegisterOnSessionInvalidated(cb func(primitive.ObjectID)) {
|
|
||||||
c.onSessionInvalidated = append(c.onSessionInvalidated, cb)
|
|
||||||
}
|
|
||||||
@ -2,7 +2,10 @@ package session
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"slices"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/go-redis/redis/v8"
|
"github.com/go-redis/redis/v8"
|
||||||
@ -42,31 +45,18 @@ func newProviderWithRedis(ctx context.Context, redisUrl string, ttl time.Duratio
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *provider_redis) New(input *Authorization) (string, error) {
|
func (p *provider_redis) New(input *Authorization) (string, error) {
|
||||||
newsk := make_storagekey(input.Account)
|
sks, err := p.RevokeAll(input.Account, false)
|
||||||
prefix := input.Account.Hex()
|
|
||||||
sks, err := p.redisClient.Keys(p.ctx, prefix+"*").Result()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Println("session provider delete :", sks, err)
|
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
p.redisClient.Del(p.ctx, sks...)
|
var newsk storagekey
|
||||||
for _, sk := range sks {
|
|
||||||
p.redisClient.Publish(p.ctx, p.deleteChannel, sk).Result()
|
|
||||||
}
|
|
||||||
|
|
||||||
for {
|
for {
|
||||||
duplicated := false
|
newsk = make_storagekey(input.Account)
|
||||||
for _, sk := range sks {
|
duplicated := slices.Contains(sks, string(newsk))
|
||||||
if sk == string(newsk) {
|
|
||||||
duplicated = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !duplicated {
|
if !duplicated {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
newsk = make_storagekey(input.Account)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = p.redisClient.HSet(p.ctx, string(newsk), input.ToStrings()).Result()
|
_, err = p.redisClient.HSet(p.ctx, string(newsk), input.ToStrings()).Result()
|
||||||
@ -81,20 +71,28 @@ func (p *provider_redis) New(input *Authorization) (string, error) {
|
|||||||
return string(pk), err
|
return string(pk), err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *provider_redis) RevokeAll(account primitive.ObjectID) error {
|
func (p *provider_redis) RevokeAll(account primitive.ObjectID, infinite bool) ([]string, error) {
|
||||||
prefix := account.Hex()
|
prefix := account.Hex()
|
||||||
sks, err := p.redisClient.Keys(p.ctx, prefix+"*").Result()
|
sks, err := p.redisClient.Keys(p.ctx, prefix+"*").Result()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Println("session provider delete :", sks, err)
|
logger.Println("session provider delete :", sks, err)
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, sk := range sks {
|
if len(sks) > 0 {
|
||||||
p.redisClient.HSet(p.ctx, sk, "inv", "true")
|
p.redisClient.Del(p.ctx, sks...)
|
||||||
p.redisClient.Publish(p.ctx, p.deleteChannel, sk).Result()
|
|
||||||
|
invsess := InvalidatedSession{
|
||||||
|
SessionKeys: sks,
|
||||||
|
Account: account,
|
||||||
|
Infinite: infinite,
|
||||||
|
}
|
||||||
|
data, _ := json.Marshal(invsess)
|
||||||
|
|
||||||
|
p.redisClient.Publish(p.ctx, p.deleteChannel, string(data)).Result()
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return sks, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *provider_redis) Query(pk string) (Authorization, error) {
|
func (p *provider_redis) Query(pk string) (Authorization, error) {
|
||||||
@ -180,12 +178,18 @@ func newConsumerWithRedis(ctx context.Context, redisUrl string, ttl time.Duratio
|
|||||||
|
|
||||||
switch msg.Channel {
|
switch msg.Channel {
|
||||||
case deleteChannel:
|
case deleteChannel:
|
||||||
sk := storagekey(msg.Payload)
|
var invsess InvalidatedSession
|
||||||
old := consumer.delete(sk)
|
if err := json.Unmarshal([]byte(msg.Payload), &invsess); err != nil {
|
||||||
if old != nil {
|
logger.Println("redis consumer deleteChannel unmarshal failed :", err)
|
||||||
for _, f := range consumer.onSessionInvalidated {
|
break
|
||||||
f(old.Account)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for _, sk := range invsess.SessionKeys {
|
||||||
|
consumer.delete(storagekey(sk))
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, f := range consumer.onSessionInvalidated {
|
||||||
|
f(invsess)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -243,37 +247,49 @@ func (c *consumer_redis) query_internal(sk storagekey) (*sessionRedis, error) {
|
|||||||
expireAt: time.Now().Add(ttl),
|
expireAt: time.Now().Add(ttl),
|
||||||
}
|
}
|
||||||
|
|
||||||
if auth.Invalidated() {
|
if auth.Valid() {
|
||||||
c.stages[0].deleted[sk] = si
|
|
||||||
} else {
|
|
||||||
c.add_internal(sk, si)
|
c.add_internal(sk, si)
|
||||||
|
} else {
|
||||||
|
c.stages[0].deleted[sk] = si
|
||||||
}
|
}
|
||||||
|
|
||||||
return si, nil
|
return si, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *consumer_redis) Query(pk string) (Authorization, error) {
|
var errRevoked = errors.New("session revoked")
|
||||||
|
var errExpired = errors.New("session expired")
|
||||||
|
|
||||||
|
func (c *consumer_redis) Query(pk string) Authorization {
|
||||||
c.lock.Lock()
|
c.lock.Lock()
|
||||||
defer c.lock.Unlock()
|
defer c.lock.Unlock()
|
||||||
|
|
||||||
sk := publickey_to_storagekey(publickey(pk))
|
sk := publickey_to_storagekey(publickey(pk))
|
||||||
|
|
||||||
|
if _, deleted := c.stages[0].deleted[sk]; deleted {
|
||||||
|
return Authorization{}
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, deleted := c.stages[1].deleted[sk]; deleted {
|
||||||
|
return Authorization{}
|
||||||
|
}
|
||||||
|
|
||||||
si, err := c.query_internal(sk)
|
si, err := c.query_internal(sk)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Println("session consumer query :", pk, err)
|
logger.Println("session consumer query :", pk, err)
|
||||||
return Authorization{}, err
|
return Authorization{}
|
||||||
}
|
}
|
||||||
|
|
||||||
if si == nil {
|
if si == nil {
|
||||||
logger.Println("session consumer query(si nil) :", pk, nil)
|
logger.Println("session consumer query(si nil) :", pk, nil)
|
||||||
return Authorization{}, nil
|
return Authorization{}
|
||||||
}
|
}
|
||||||
|
|
||||||
if time.Now().After(si.expireAt) {
|
if time.Now().After(si.expireAt) {
|
||||||
logger.Println("session consumer query(expired):", pk, nil)
|
logger.Println("session consumer query(expired):", pk, nil)
|
||||||
return Authorization{}, nil
|
return Authorization{}
|
||||||
}
|
}
|
||||||
|
|
||||||
return *si.Authorization, nil
|
return *si.Authorization
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *consumer_redis) Touch(pk string) (Authorization, error) {
|
func (c *consumer_redis) Touch(pk string) (Authorization, error) {
|
||||||
@ -353,6 +369,6 @@ func (c *consumer_redis) IsRevoked(accid primitive.ObjectID) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *consumer_redis) RegisterOnSessionInvalidated(cb func(primitive.ObjectID)) {
|
func (c *consumer_redis) RegisterOnSessionInvalidated(cb func(InvalidatedSession)) {
|
||||||
c.onSessionInvalidated = append(c.onSessionInvalidated, cb)
|
c.onSessionInvalidated = append(c.onSessionInvalidated, cb)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -60,11 +60,11 @@ func TestExpTable(t *testing.T) {
|
|||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
for {
|
for {
|
||||||
q1, err := cs.Query(sk1)
|
q1 := cs.Query(sk1)
|
||||||
logger.Println("query :", q1, err)
|
logger.Println("query :", q1)
|
||||||
|
|
||||||
q2, err := cs.Query(sk2)
|
q2 := cs.Query(sk2)
|
||||||
logger.Println("query :", q2, err)
|
logger.Println("query :", q2)
|
||||||
time.Sleep(time.Second)
|
time.Sleep(time.Second)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
@ -75,7 +75,7 @@ func TestExpTable(t *testing.T) {
|
|||||||
time.Sleep(2 * time.Second)
|
time.Sleep(2 * time.Second)
|
||||||
|
|
||||||
time.Sleep(2 * time.Second)
|
time.Sleep(2 * time.Second)
|
||||||
pv.RevokeAll(au1.Account)
|
pv.RevokeAll(au1.Account, false)
|
||||||
|
|
||||||
cs.Touch(sk1)
|
cs.Touch(sk1)
|
||||||
time.Sleep(2 * time.Second)
|
time.Sleep(2 * time.Second)
|
||||||
@ -87,7 +87,7 @@ func TestExpTable(t *testing.T) {
|
|||||||
t.Error(err)
|
t.Error(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
q2, err := cs2.Query(sk2)
|
q2 := cs2.Query(sk2)
|
||||||
logger.Println("queryf :", q2, err)
|
logger.Println("queryf :", q2)
|
||||||
time.Sleep(20 * time.Second)
|
time.Sleep(20 * time.Second)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -334,8 +334,8 @@ func (ws *WebsocketHandler) LeaveRoom(room string, accid primitive.ObjectID) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ws *WebsocketHandler) onSessionInvalidated(accid primitive.ObjectID) {
|
func (ws *WebsocketHandler) onSessionInvalidated(invsess session.InvalidatedSession) {
|
||||||
ws.forceCloseChan <- accid
|
ws.forceCloseChan <- invsess.Account
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ws *WebsocketHandler) mainLoop(ctx context.Context) {
|
func (ws *WebsocketHandler) mainLoop(ctx context.Context) {
|
||||||
@ -364,14 +364,15 @@ func (ws *WebsocketHandler) mainLoop(ctx context.Context) {
|
|||||||
buffer := bytes.NewBuffer([]byte(raw.Payload))
|
buffer := bytes.NewBuffer([]byte(raw.Payload))
|
||||||
dec := gob.NewDecoder(buffer)
|
dec := gob.NewDecoder(buffer)
|
||||||
|
|
||||||
if raw.Channel == ws.redisMsgChanName {
|
switch raw.Channel {
|
||||||
|
case ws.redisMsgChanName:
|
||||||
var msg UpstreamMessage
|
var msg UpstreamMessage
|
||||||
if err := dec.Decode(&msg); err == nil {
|
if err := dec.Decode(&msg); err == nil {
|
||||||
ws.deliveryChan <- &msg
|
ws.deliveryChan <- &msg
|
||||||
} else {
|
} else {
|
||||||
logger.Println("decode UpstreamMessage failed :", err)
|
logger.Println("decode UpstreamMessage failed :", err)
|
||||||
}
|
}
|
||||||
} else if raw.Channel == ws.redisCmdChanName {
|
case ws.redisCmdChanName:
|
||||||
var cmd commandMessage
|
var cmd commandMessage
|
||||||
if err := dec.Decode(&cmd); err == nil {
|
if err := dec.Decode(&cmd); err == nil {
|
||||||
ws.deliveryChan <- &cmd
|
ws.deliveryChan <- &cmd
|
||||||
@ -587,6 +588,8 @@ func (ws *WebsocketHandler) mainLoop(ctx context.Context) {
|
|||||||
if c.Conn == nil {
|
if c.Conn == nil {
|
||||||
delete(entireConns, c.sender.Accid.Hex())
|
delete(entireConns, c.sender.Accid.Hex())
|
||||||
go ws.ClientDisconnected(c)
|
go ws.ClientDisconnected(c)
|
||||||
|
} else if ws.sessionConsumer.IsRevoked(c.sender.Accid) {
|
||||||
|
c.Conn.MakeWriter().WriteControl(websocket.CloseMessage, unauthdata, time.Time{})
|
||||||
} else {
|
} else {
|
||||||
entireConns[c.sender.Accid.Hex()] = c
|
entireConns[c.sender.Accid.Hex()] = c
|
||||||
go ws.ClientConnected(c)
|
go ws.ClientConnected(c)
|
||||||
@ -680,18 +683,13 @@ func (ws *WebsocketHandler) upgrade_nosession(w http.ResponseWriter, r *http.Req
|
|||||||
accid := primitive.ObjectID(*raw)
|
accid := primitive.ObjectID(*raw)
|
||||||
|
|
||||||
sk := r.Header.Get("AS-X-SESSION")
|
sk := r.Header.Get("AS-X-SESSION")
|
||||||
authinfo, err := ws.sessionConsumer.Query(sk)
|
authinfo := ws.sessionConsumer.Query(sk)
|
||||||
if err != nil {
|
if !authinfo.Valid() {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if authinfo.Account != accid {
|
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if authinfo.Invalidated() {
|
if authinfo.Account != accid {
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -734,19 +732,8 @@ func (ws *WebsocketHandler) upgrade(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
authinfo, err := ws.sessionConsumer.Query(sk)
|
authinfo := ws.sessionConsumer.Query(sk)
|
||||||
if err != nil {
|
if !authinfo.Valid() {
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
|
||||||
logger.Error("authorize query failed :", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if authinfo.Account.IsZero() {
|
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if authinfo.Invalidated() {
|
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@ -176,9 +176,9 @@ func (ws *websocketPeerHandler[T]) RegisterHandlers(serveMux gocommon.ServerMuxI
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ws *websocketPeerHandler[T]) onSessionInvalidated(accid primitive.ObjectID) {
|
func (ws *websocketPeerHandler[T]) onSessionInvalidated(invsess session.InvalidatedSession) {
|
||||||
ws.peerDtorChannel <- peerDtorChannelValue{
|
ws.peerDtorChannel <- peerDtorChannelValue{
|
||||||
accid: accid,
|
accid: invsess.Account,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -305,10 +305,12 @@ func (ws *websocketPeerHandler[T]) upgrade_noauth(w http.ResponseWriter, r *http
|
|||||||
sk := r.Header.Get("AS-X-SESSION")
|
sk := r.Header.Get("AS-X-SESSION")
|
||||||
var accid primitive.ObjectID
|
var accid primitive.ObjectID
|
||||||
if len(sk) > 0 {
|
if len(sk) > 0 {
|
||||||
authinfo, err := ws.sessionConsumer.Query(sk)
|
authinfo := ws.sessionConsumer.Query(sk)
|
||||||
if err == nil {
|
if !authinfo.Valid() {
|
||||||
accid = authinfo.Account
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
accid = authinfo.Account
|
||||||
}
|
}
|
||||||
|
|
||||||
if accid.IsZero() {
|
if accid.IsZero() {
|
||||||
@ -363,14 +365,8 @@ func (ws *websocketPeerHandler[T]) upgrade(w http.ResponseWriter, r *http.Reques
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
sk := r.Header.Get("AS-X-SESSION")
|
sk := r.Header.Get("AS-X-SESSION")
|
||||||
authinfo, err := ws.sessionConsumer.Query(sk)
|
authinfo := ws.sessionConsumer.Query(sk)
|
||||||
if err != nil {
|
if !authinfo.Valid() {
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
|
||||||
logger.Error("authorize query failed :", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if authinfo.Account.IsZero() || authinfo.Invalidated() {
|
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user