liujiandao
2024-02-20 4860c7b312cdce2d948ee417b0bb1fed60fd9dc7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
package cache
 
import (
    "encoding/base64"
    "errors"
    "flag"
    "fmt"
    "strconv"
    "strings"
    "sync"
    "time"
 
    "sdkCompare/cache/shardmap"
    "sdkCompare/config"
    "sdkCompare/util"
 
    libEs "basic.com/pubsub/esutil.git"
    "basic.com/pubsub/protomsg.git"
    "basic.com/valib/logger.git"
    "github.com/golang/protobuf/proto"
)
 
var querynum = flag.Int("querynum", 3000, "the query number from database")
var threadnum = flag.Int("threadnum", 32, "the number of thread to deal data.")
 
var (
    thresholdLimit     = float32(50)
    captureTable       = "capturetable"
    cartable           = "carTable_"
    PRE_DBTABLE        = "dbTable_"
    PRE_CAPTURE_SERVER = "captureServer_"
)
 
type CmapItem struct {
    sync.Mutex
    Cam map[string]*shardmap.ShardMap
}
 
var Cmap *CmapItem
var doOnce sync.Once
 
// 计算每次查询的数据量条数
func Querynum(totalnum int) int {
    qn := totalnum / *threadnum //qn=6551
    if *querynum < qn {         //
 
        return *querynum
    }
    return qn
}
 
// 增量查询
func IncreVideoPersonsCache(lastT time.Time, targetType string) {
    ticker := time.NewTicker(time.Minute * 3)
    for {
        select {
        case <-ticker.C:
            curTime := time.Now()
            Incrementquery(lastT, curTime, targetType)
            lastT = curTime
        }
    }
}
 
func Incrementquery(last time.Time, cur time.Time, targetType string) {
    laststring := last.Format("2006-01-02 15:04:05")
    curstring := cur.Format("2006-01-02 15:04:05")
    alarmIp := config.EsCompServerInfo.ESIP
    alarmPort := config.EsCompServerInfo.ESPort
    indexName := config.EsInfo.EsIndex.AiOcean.IndexName
 
    serverIp, _, e := util.GetLocalIP(config.Server.NetworkAdapter)
    if e != nil {
        return
    }
 
    shardStr, e := getShards(serverIp, alarmIp, alarmPort)
    if e != nil {
        return
    }
 
    // 调用增量的接口
    captures, err := libEs.GetPeriodInfos(serverIp, alarmPort, laststring, curstring, indexName, shardStr, targetType)
    if err != nil {
        logger.Error(err)
        return
    }
    for _, ei := range captures {
        if ei.EsInfo.AnalyServerId != "" {
            cKey := PRE_CAPTURE_SERVER + ei.EsInfo.AnalyServerId
            ei.EsInfo.Tableid = captureTable
 
            if _, ok := Cmap.Cam[cKey]; !ok {
                Cmap.Cam[cKey] = shardmap.New(uint8(*threadnum))
            }
 
            Cmap.Cam[cKey].Set(ei.EsInfo.Id, ei.EsInfo)
        }
    }
}
 
func getShards(serverIp string, alarmIp string, alarmPort string) (string, error) {
    infos, e := libEs.GetShardsByIndex(alarmIp, alarmPort, config.EsInfo.EsIndex.AiOcean.IndexName)
    if e != nil || infos == nil {
        logger.Error("get es primary ips err")
        return "", errors.New("get es primary ips err")
    }
 
    var shards []string
    for _, shard := range infos {
        if (shard.ShardIp == serverIp || shard.ShardIp == "127.0.0.1") && shard.ShardRole == "primary" && shard.ShardState == "STARTED" {
            shards = append(shards, strconv.Itoa(shard.ShardNum))
        }
    }
    if len(shards) == 0 {
        return "", errors.New("current shards is empty")
    }
    return strings.Join(shards, ","), nil
}
 
// 1. 拿到总量, 计算每个线程的查询量
// 2. 分线程查询
func Init(indexName string, targetType string) error {
    alarmIp := config.EsCompServerInfo.ESIP
    alarmPort := config.EsCompServerInfo.ESPort
 
    doOnce.Do(func() {
        flag.Parse()
 
        Cmap = &CmapItem{
            Cam: make(map[string]*shardmap.ShardMap),
        }
    })
 
    serverIp, _, e := util.GetLocalIP(config.Server.NetworkAdapter)
    if e != nil {
        return e
    }
 
    shardStr, e := getShards(serverIp, alarmIp, alarmPort)
    if e != nil {
        return e
    }
    // 这里需要提供总量的接口
    estotalnum := libEs.GetTotal(serverIp, alarmPort, indexName, shardStr, targetType)
    *querynum = Querynum(estotalnum)
    temptime := time.Now()
 
    captures, err := libEs.GetOceanFeatures(serverIp, alarmPort, 1000, indexName, shardStr, targetType)
    if err != nil {
        logger.Error("libEs.GetOceanFeatures err:", err)
        return err
    }
    logger.Debug("len(captures):", len(captures))
    Cmap.Lock()
    for _, ei := range captures {
        if ei.EsInfo.AnalyServerId != "" {
            cKey := PRE_CAPTURE_SERVER + ei.EsInfo.AnalyServerId
            ei.EsInfo.Tableid = captureTable
            if _, ok := Cmap.Cam[cKey]; !ok {
                Cmap.Cam[cKey] = shardmap.New(uint8(*threadnum))
            }
 
            Cmap.Cam[cKey].Set(ei.EsInfo.Id, ei.EsInfo)
        }
    }
 
    Cmap.Unlock()
 
    logger.Debug(indexName, "缓存完成用时:", time.Since(temptime))
    return nil
}
 
func ReInitDbTablePersonsCache() {
    Cmap.Lock()
    defer Cmap.Unlock()
    if Cmap == nil {
        Cmap = &CmapItem{
            Cam: make(map[string]*shardmap.ShardMap),
        }
    }
    for tableId, _ := range Cmap.Cam {
        delete(Cmap.Cam, tableId)
    }
 
    initDbTablePersonsCache()
}
 
func InitDbTablePersons() {
    doOnce.Do(func() {
        flag.Parse()
 
        Cmap = &CmapItem{
            Cam: make(map[string]*shardmap.ShardMap),
        }
    })
 
    initDbTablePersonsCache()
}
 
func initDbTablePersonsCache() {
    // 查询所有的底库列表
    var dtApi DbTables
    allTables, err := dtApi.FindAllDbTablesByCurServer()
    if err == nil && allTables != nil && len(allTables) > 0 { //初始化底库缓存信息
        Cmap.Lock()
        for _, table := range allTables {
            if _, ok := Cmap.Cam[PRE_DBTABLE]; !ok {
                Cmap.Cam[PRE_DBTABLE] = shardmap.New(uint8(*threadnum))
            }
            Cmap.Cam[PRE_DBTABLE].Set(table.Id, table.Enable == 1)
            logger.Debugf("初始化底库[%s][%s]到缓存中", table.Id, table.TableName)
        }
        Cmap.Unlock()
    }
 
    // 缓存底库中的全部人员信息
    var dbpApi DbPersons
    total, e := dbpApi.GetPersonTotal("")
    logger.Debugf("所有底库共有%d条记录", total)
    if e == nil && total > 0 {
        queryEachNum := *querynum
        qn := int(total) / *threadnum
        if *querynum < qn {
            queryEachNum = qn
        }
        queryT := int(total) / queryEachNum
        if int(total)%queryEachNum > 0 {
            queryT++
        }
        temptime := time.Now()
        var wg sync.WaitGroup
 
        for i := 0; i < queryT; i++ {
            j := i * queryEachNum
            wg.Add(1)
            go func(qs int) {
                defer wg.Done()
                dbpersons, err := dbpApi.GetPersonsCompareCacheBase(j, queryEachNum)
                if err != nil {
                    logger.Error(err)
                    return
                }
                logger.Debugf("获取%d条人员信息", len(dbpersons))
                Cmap.Lock()
                tableId := ""
                for _, value := range dbpersons {
                    tableId = value.Tableid
                    if _, ok := Cmap.Cam[value.Tableid]; !ok {
                        Cmap.Cam[value.Tableid] = shardmap.New(uint8(*threadnum))
                    }
 
                    Cmap.Cam[value.Tableid].Set(value.Id, value)
                }
 
                if len(dbpersons) != 0 {
                    Cmap.Cam[tableId].Settime()
                }
 
                Cmap.Unlock()
 
            }(j)
        }
        wg.Wait()
        logger.Debug("底库人员缓存完成用时:", time.Since(temptime))
    }
}
 
// UpdateDbPersonsCacheById 更新缓存中的全部人员信息
func UpdateDbPersonsCacheById(id string) {
    var dbpApi DbPersons
    info, err := dbpApi.GetPersonsCompareCacheById(id)
    if err != nil {
        logger.Error(err)
        return
    }
    if info.Tableid != "" {
        Cmap.Lock()
        defer Cmap.Unlock()
        if _, ok := Cmap.Cam[info.Tableid]; !ok {
            Cmap.Cam[info.Tableid] = shardmap.New(uint8(*threadnum))
        }
        Cmap.Cam[info.Tableid].Set(info.Id, info)
        Cmap.Cam[info.Tableid].Settime()
    }
}
 
func RealTimeAddPersonInfoToCache(tableId string, id string, faceFeature string, enable int32, carNo string) {
    Cmap.Lock()
    defer Cmap.Unlock()
    if _, ok := Cmap.Cam[tableId]; !ok {
        Cmap.Cam[tableId] = shardmap.New(uint8(*threadnum))
    }
    var ei = protomsg.Esinfo{
        Id:          id,
        Tableid:     tableId,
        FaceFeature: faceFeature,
        Enable:      enable,
        CarNo:       carNo,
    }
    Cmap.Cam[tableId].Set(id, &ei)
    logger.Debug("id:", id, ",tableId:", ",len(faceFeature):", len(faceFeature), ",tableId:", tableId, ",enable:", enable)
}
 
func RealTimeDelPersonFromCache(tableId string, id string) {
    logger.Debug("DelPersonFromCache,tableId:", tableId, ",id:", id)
    Cmap.Lock()
    defer Cmap.Unlock()
    if _, ok := Cmap.Cam[tableId]; ok {
        Cmap.Cam[tableId].Del(id)
        logger.Debug("DelPerson ok success")
    } else {
        logger.Error("tableId:", tableId, " not exist")
    }
}
 
func RealTimeDelTable(tableId string) {
    logger.Debug("RealTimeDelTable tableId:", tableId)
    Cmap.Lock()
    defer Cmap.Unlock()
 
    if dtM, ok := Cmap.Cam[PRE_DBTABLE]; ok {
        dtM.Del(tableId)
    }
    if _, ok := Cmap.Cam[tableId]; ok {
        delete(Cmap.Cam, tableId)
    }
}
 
// 使底库生效,将底库中的所有生效状态的人特征添加到缓存
func RealTimeUpdateTable(tableId string, enable int32) {
    logger.Debug("RealTimeUpdateTable tableId:", tableId, ",enable:", enable)
    Cmap.Lock()
    defer Cmap.Unlock()
 
    if _, ok := Cmap.Cam[PRE_DBTABLE]; !ok {
        Cmap.Cam[PRE_DBTABLE] = shardmap.New(uint8(*threadnum))
    }
    Cmap.Cam[PRE_DBTABLE].Set(tableId, enable == 1)
}
 
func UpdateCache(changeMsg *protomsg.EsPersonCacheChange) {
    if changeMsg.Type == protomsg.EsCacheChanged_T_DbTable {
        if changeMsg.Action == protomsg.DbAction_Insert || changeMsg.Action == protomsg.DbAction_Update {
            RealTimeUpdateTable(changeMsg.TableId[0], changeMsg.Enable)
        } else if changeMsg.Action == protomsg.DbAction_Delete {
            RealTimeDelTable(changeMsg.TableId[0])
        }
    } else if changeMsg.Type == protomsg.EsCacheChanged_T_DbTablePerson {
        if changeMsg.Action == protomsg.DbAction_Insert || changeMsg.Action == protomsg.DbAction_Update {
            RealTimeAddPersonInfoToCache(changeMsg.TableId[0], changeMsg.PersonId, changeMsg.Feature, changeMsg.Enable, changeMsg.CarNo)
        } else if changeMsg.Action == protomsg.DbAction_Delete {
            RealTimeDelPersonFromCache(changeMsg.TableId[0], changeMsg.PersonId)
        }
    }
}
 
func GetComparePersonBaseInfo(compareArgs protomsg.CompareArgs) []byte {
    if compareArgs.FaceFeature == nil {
        return nil
    }
 
    //指定最低分
    baseScore := thresholdLimit
    if compareArgs.CompareThreshold > thresholdLimit {
        baseScore = compareArgs.CompareThreshold
    }
 
    if compareArgs.IsCompareAll {
        baseScore = 0
    }
 
    var scResult protomsg.SdkCompareResult
 
    //未指定比对目标map
    if compareArgs.TableIds == nil || len(compareArgs.TableIds) == 0 {
        logger.Debugf("接收到底库比对请求, 阈值:%f", compareArgs.CompareThreshold)
 
        // 比对来源是ruleprocess,传空比全部底库
        if !compareArgs.Source {
            for key, val := range Cmap.Cam {
                // 判断是否属于底库
                if tShard, hasT := Cmap.Cam[PRE_DBTABLE]; hasT {
                    if tEnable, tOk := tShard.Get(key); tOk { //存在此底库
                        //底库有效
                        if tEnable.(bool) {
                            targets := val.Walk(DoSdkCompare, compareArgs.FaceFeature, baseScore, compareArgs.Source, compareArgs.CompareTarget)
                            if len(targets) > 0 {
                                scResult.CompareResult = append(scResult.CompareResult, targets...)
                            }
                        }
                    }
                }
            }
        } else { //来源是web,比对所有抓拍和底库
            for cKey, val := range Cmap.Cam {
                if compareArgs.AnalyServerId != "" { //比对指定server产生的抓拍数据和底库
                    if cKey == PRE_CAPTURE_SERVER+compareArgs.AnalyServerId || !strings.HasPrefix(cKey, PRE_CAPTURE_SERVER) {
                        targets := val.Walk(DoSdkCompare, compareArgs.FaceFeature, baseScore, compareArgs.Source, compareArgs.CompareTarget)
                        if len(targets) > 0 {
                            scResult.CompareResult = append(scResult.CompareResult, targets...)
                        }
                    }
                } else { //管理平台请求,比对所有数据
                    if len(compareArgs.ServerIds) > 0 {
                        for _, termDevId := range compareArgs.ServerIds {
                            if cKey == PRE_CAPTURE_SERVER+termDevId || !strings.HasPrefix(cKey, PRE_CAPTURE_SERVER) {
                                targets := val.Walk(DoSdkCompare, compareArgs.FaceFeature, baseScore, compareArgs.Source, compareArgs.CompareTarget)
                                if len(targets) > 0 {
                                    scResult.CompareResult = append(scResult.CompareResult, targets...)
                                }
                            }
                        }
                    } else {
                        targets := val.Walk(DoSdkCompare, compareArgs.FaceFeature, baseScore, compareArgs.Source, compareArgs.CompareTarget)
                        if len(targets) > 0 {
                            scResult.CompareResult = append(scResult.CompareResult, targets...)
                        }
                    }
                }
            }
        }
    } else { //指定比对目标map
        if !compareArgs.Source {
            for _, tid := range compareArgs.TableIds { //ruleProcess比对指定底库
                shardins, ok := Cmap.Cam[tid]
                if !ok {
                    logger.Error("ruleProcess compare get shard error by tableId:", tid)
                    continue
                }
                if tShard, hasT := Cmap.Cam[PRE_DBTABLE]; hasT {
                    if tEnable, tOk := tShard.Get(tid); tOk { //存在此底库
                        logger.Debug("ruleProcess compare tables,exist tableId:", tid, ",enable:", tEnable)
                        if tEnable.(bool) { //底库有效
                            targets := shardins.Walk(DoSdkCompare, compareArgs.FaceFeature, baseScore, compareArgs.Source, compareArgs.CompareTarget)
                            if len(targets) > 0 {
                                scResult.CompareResult = append(scResult.CompareResult, targets...)
                            }
                        }
                    } else {
                        logger.Error("ruleProcess compare tables,tShard not exist tableId:", tid)
                    }
                } else {
                    logger.Error("ruleProcess compare tables,PRE_DBTABLE tableId:", tid, " not exist")
                }
            }
        } else { //web请求,比对指定的抓拍库或者底库
            for _, tid := range compareArgs.TableIds {
                if tid == captureTable { //比对抓拍库
                    tStart := time.Now()
                    serverIp, _, e := util.GetLocalIP(config.Server.NetworkAdapter)
                    if e != nil {
                        logger.Error("util.GetLocalIP err:", e)
                        continue
                    }
                    alarmPort := config.EsCompServerInfo.ESPort
 
                    scopeIds := libEs.GetAllLocalVideopersonsId(compareArgs, config.EsInfo.EsIndex.AiOcean.IndexName, serverIp, alarmPort, compareArgs.AlarmLevel)
                    logger.Debug("libEs.GetAllLocalVideopersonsId len(scopeIds):", len(scopeIds), " 耗时:", time.Since(tStart))
                    if scopeIds != nil {
                        tCompStart := time.Now()
                        if compareArgs.AnalyServerId != "" { //指定server
                            for cKey, cacheMap := range Cmap.Cam {
                                if cKey == PRE_CAPTURE_SERVER+compareArgs.AnalyServerId {
                                    for _, sId := range scopeIds {
                                        obj, ok := cacheMap.Get(sId)
                                        if ok {
                                            eInfo, ok := obj.(*protomsg.Esinfo)
                                            if !ok {
                                                continue
                                            }
                                            sec := DoSdkCompare(compareArgs.FaceFeature, eInfo.FaceFeature)
                                            if sec >= baseScore {
                                                scResult.CompareResult = append(scResult.CompareResult, &protomsg.SdkCompareEach{
                                                    Id:           eInfo.Id,
                                                    CompareScore: sec,
                                                    Tableid:      eInfo.Tableid,
                                                })
                                            }
                                        }
                                    }
                                }
                            }
                        } else { //管理平台请求比对所有抓拍,不指定server
                            for cKey, cacheMap := range Cmap.Cam {
                                if len(compareArgs.ServerIds) > 0 {
                                    for _, termDevId := range compareArgs.ServerIds {
                                        if cKey == PRE_CAPTURE_SERVER+termDevId || !strings.HasPrefix(cKey, PRE_CAPTURE_SERVER) {
                                            targets := cacheMap.Walk(DoSdkCompare, compareArgs.FaceFeature, baseScore, compareArgs.Source, compareArgs.CompareTarget)
                                            if len(targets) > 0 {
                                                scResult.CompareResult = append(scResult.CompareResult, targets...)
                                            }
                                        }
                                    }
                                } else {
                                    if strings.HasPrefix(cKey, PRE_CAPTURE_SERVER) {
                                        for _, sId := range scopeIds {
                                            if obj, ok := cacheMap.Get(sId); ok {
                                                eInfo, ok := obj.(*protomsg.Esinfo)
                                                if !ok {
                                                    continue
                                                }
                                                sec := DoSdkCompare(compareArgs.FaceFeature, eInfo.FaceFeature)
                                                if sec >= baseScore {
                                                    scResult.CompareResult = append(scResult.CompareResult, &protomsg.SdkCompareEach{
                                                        Id:           eInfo.Id,
                                                        CompareScore: sec,
                                                        Tableid:      eInfo.Tableid,
                                                    })
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        logger.Debug("根据scopeIds比对耗时:", time.Since(tCompStart))
                    }
                } else {
                    shardins, ok := Cmap.Cam[tid]
                    if !ok {
                        logger.Error("get shard error by tableId:", tid)
                        continue
                    }
 
                    targets := shardins.Walk(DoSdkCompare, compareArgs.FaceFeature, baseScore, compareArgs.Source, compareArgs.CompareTarget)
                    if len(targets) > 0 {
                        scResult.CompareResult = append(scResult.CompareResult, targets...)
                    }
                }
            }
        }
    }
 
    logger.Debug("比对结果: len(scResult.CompareResult):", len(scResult.CompareResult))
    buf, err := proto.Marshal(&scResult)
 
    if err != nil {
        logger.Error("scResult Marshal error!", err)
        return nil
    }
 
    return buf
}
 
func DoSdkCompare(ci []byte, co string) float32 {
 
    co_d, err := base64.StdEncoding.DecodeString(co)
    if err != nil {
        logger.Error("DoSdkCompare err:", err)
        return -1
    }
    if len(co_d) != 2560 {
        logger.Error("target fea.len !=2560")
        return -1
    }
 
    if len(ci) != 2560 {
        logger.Error("source fea.len !=2560")
        return -1
    }
    sec := DecCompare(ci, co_d)
    //logger.Debug("比对得分为:", sec)
 
    sec = ParseScore(sec)
    return sec
}
 
func ParseScore(compareScore float32) float32 {
    if compareScore <= 1 {
        compareScore = compareScore * 100
    }
    if compareScore == 100 {
        return 100
    }
    f, _ := strconv.ParseFloat(fmt.Sprintf("%2.2f", compareScore), 32)
 
    return float32(f)
}