channel-test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. package controller
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "math"
  9. "net/http"
  10. "net/http/httptest"
  11. "net/url"
  12. "one-api/common"
  13. "one-api/constant"
  14. "one-api/dto"
  15. "one-api/middleware"
  16. "one-api/model"
  17. "one-api/relay"
  18. relaycommon "one-api/relay/common"
  19. relayconstant "one-api/relay/constant"
  20. "one-api/relay/helper"
  21. "one-api/service"
  22. "one-api/setting/operation_setting"
  23. "one-api/types"
  24. "strconv"
  25. "strings"
  26. "sync"
  27. "time"
  28. "github.com/bytedance/gopkg/util/gopool"
  29. "github.com/samber/lo"
  30. "github.com/gin-gonic/gin"
  31. )
  32. type testResult struct {
  33. context *gin.Context
  34. localErr error
  35. newAPIError *types.NewAPIError
  36. }
  37. func testChannel(channel *model.Channel, testModel string, endpointType string) testResult {
  38. tik := time.Now()
  39. var unsupportedTestChannelTypes = []int{
  40. constant.ChannelTypeMidjourney,
  41. constant.ChannelTypeMidjourneyPlus,
  42. constant.ChannelTypeSunoAPI,
  43. constant.ChannelTypeKling,
  44. constant.ChannelTypeJimeng,
  45. constant.ChannelTypeDoubaoVideo,
  46. constant.ChannelTypeVidu,
  47. }
  48. if lo.Contains(unsupportedTestChannelTypes, channel.Type) {
  49. channelTypeName := constant.GetChannelTypeName(channel.Type)
  50. return testResult{
  51. localErr: fmt.Errorf("%s channel test is not supported", channelTypeName),
  52. }
  53. }
  54. w := httptest.NewRecorder()
  55. c, _ := gin.CreateTestContext(w)
  56. testModel = strings.TrimSpace(testModel)
  57. if testModel == "" {
  58. if channel.TestModel != nil && *channel.TestModel != "" {
  59. testModel = strings.TrimSpace(*channel.TestModel)
  60. } else {
  61. models := channel.GetModels()
  62. if len(models) > 0 {
  63. testModel = strings.TrimSpace(models[0])
  64. }
  65. if testModel == "" {
  66. testModel = "gpt-4o-mini"
  67. }
  68. }
  69. }
  70. requestPath := "/v1/chat/completions"
  71. // 如果指定了端点类型,使用指定的端点类型
  72. if endpointType != "" {
  73. if endpointInfo, ok := common.GetDefaultEndpointInfo(constant.EndpointType(endpointType)); ok {
  74. requestPath = endpointInfo.Path
  75. }
  76. } else {
  77. // 如果没有指定端点类型,使用原有的自动检测逻辑
  78. // 先判断是否为 Embedding 模型
  79. if strings.Contains(strings.ToLower(testModel), "embedding") ||
  80. strings.HasPrefix(testModel, "m3e") || // m3e 系列模型
  81. strings.Contains(testModel, "bge-") || // bge 系列模型
  82. strings.Contains(testModel, "embed") ||
  83. channel.Type == constant.ChannelTypeMokaAI { // 其他 embedding 模型
  84. requestPath = "/v1/embeddings" // 修改请求路径
  85. }
  86. // VolcEngine 图像生成模型
  87. if channel.Type == constant.ChannelTypeVolcEngine && strings.Contains(testModel, "seedream") {
  88. requestPath = "/v1/images/generations"
  89. }
  90. }
  91. c.Request = &http.Request{
  92. Method: "POST",
  93. URL: &url.URL{Path: requestPath}, // 使用动态路径
  94. Body: nil,
  95. Header: make(http.Header),
  96. }
  97. cache, err := model.GetUserCache(1)
  98. if err != nil {
  99. return testResult{
  100. localErr: err,
  101. newAPIError: nil,
  102. }
  103. }
  104. cache.WriteContext(c)
  105. //c.Request.Header.Set("Authorization", "Bearer "+channel.Key)
  106. c.Request.Header.Set("Content-Type", "application/json")
  107. c.Set("channel", channel.Type)
  108. c.Set("base_url", channel.GetBaseURL())
  109. group, _ := model.GetUserGroup(1, false)
  110. c.Set("group", group)
  111. newAPIError := middleware.SetupContextForSelectedChannel(c, channel, testModel)
  112. if newAPIError != nil {
  113. return testResult{
  114. context: c,
  115. localErr: newAPIError,
  116. newAPIError: newAPIError,
  117. }
  118. }
  119. // Determine relay format based on endpoint type or request path
  120. var relayFormat types.RelayFormat
  121. if endpointType != "" {
  122. // 根据指定的端点类型设置 relayFormat
  123. switch constant.EndpointType(endpointType) {
  124. case constant.EndpointTypeOpenAI:
  125. relayFormat = types.RelayFormatOpenAI
  126. case constant.EndpointTypeOpenAIResponse:
  127. relayFormat = types.RelayFormatOpenAIResponses
  128. case constant.EndpointTypeAnthropic:
  129. relayFormat = types.RelayFormatClaude
  130. case constant.EndpointTypeGemini:
  131. relayFormat = types.RelayFormatGemini
  132. case constant.EndpointTypeJinaRerank:
  133. relayFormat = types.RelayFormatRerank
  134. case constant.EndpointTypeImageGeneration:
  135. relayFormat = types.RelayFormatOpenAIImage
  136. case constant.EndpointTypeEmbeddings:
  137. relayFormat = types.RelayFormatEmbedding
  138. default:
  139. relayFormat = types.RelayFormatOpenAI
  140. }
  141. } else {
  142. // 根据请求路径自动检测
  143. relayFormat = types.RelayFormatOpenAI
  144. if c.Request.URL.Path == "/v1/embeddings" {
  145. relayFormat = types.RelayFormatEmbedding
  146. }
  147. if c.Request.URL.Path == "/v1/images/generations" {
  148. relayFormat = types.RelayFormatOpenAIImage
  149. }
  150. if c.Request.URL.Path == "/v1/messages" {
  151. relayFormat = types.RelayFormatClaude
  152. }
  153. if strings.Contains(c.Request.URL.Path, "/v1beta/models") {
  154. relayFormat = types.RelayFormatGemini
  155. }
  156. if c.Request.URL.Path == "/v1/rerank" || c.Request.URL.Path == "/rerank" {
  157. relayFormat = types.RelayFormatRerank
  158. }
  159. if c.Request.URL.Path == "/v1/responses" {
  160. relayFormat = types.RelayFormatOpenAIResponses
  161. }
  162. }
  163. request := buildTestRequest(testModel, endpointType)
  164. info, err := relaycommon.GenRelayInfo(c, relayFormat, request, nil)
  165. if err != nil {
  166. return testResult{
  167. context: c,
  168. localErr: err,
  169. newAPIError: types.NewError(err, types.ErrorCodeGenRelayInfoFailed),
  170. }
  171. }
  172. info.InitChannelMeta(c)
  173. err = helper.ModelMappedHelper(c, info, request)
  174. if err != nil {
  175. return testResult{
  176. context: c,
  177. localErr: err,
  178. newAPIError: types.NewError(err, types.ErrorCodeChannelModelMappedError),
  179. }
  180. }
  181. testModel = info.UpstreamModelName
  182. // 更新请求中的模型名称
  183. request.SetModelName(testModel)
  184. apiType, _ := common.ChannelType2APIType(channel.Type)
  185. adaptor := relay.GetAdaptor(apiType)
  186. if adaptor == nil {
  187. return testResult{
  188. context: c,
  189. localErr: fmt.Errorf("invalid api type: %d, adaptor is nil", apiType),
  190. newAPIError: types.NewError(fmt.Errorf("invalid api type: %d, adaptor is nil", apiType), types.ErrorCodeInvalidApiType),
  191. }
  192. }
  193. //// 创建一个用于日志的 info 副本,移除 ApiKey
  194. //logInfo := info
  195. //logInfo.ApiKey = ""
  196. common.SysLog(fmt.Sprintf("testing channel %d with model %s , info %+v ", channel.Id, testModel, info.ToString()))
  197. priceData, err := helper.ModelPriceHelper(c, info, 0, request.GetTokenCountMeta())
  198. if err != nil {
  199. return testResult{
  200. context: c,
  201. localErr: err,
  202. newAPIError: types.NewError(err, types.ErrorCodeModelPriceError),
  203. }
  204. }
  205. adaptor.Init(info)
  206. var convertedRequest any
  207. // 根据 RelayMode 选择正确的转换函数
  208. switch info.RelayMode {
  209. case relayconstant.RelayModeEmbeddings:
  210. // Embedding 请求 - request 已经是正确的类型
  211. if embeddingReq, ok := request.(*dto.EmbeddingRequest); ok {
  212. convertedRequest, err = adaptor.ConvertEmbeddingRequest(c, info, *embeddingReq)
  213. } else {
  214. return testResult{
  215. context: c,
  216. localErr: errors.New("invalid embedding request type"),
  217. newAPIError: types.NewError(errors.New("invalid embedding request type"), types.ErrorCodeConvertRequestFailed),
  218. }
  219. }
  220. case relayconstant.RelayModeImagesGenerations:
  221. // 图像生成请求 - request 已经是正确的类型
  222. if imageReq, ok := request.(*dto.ImageRequest); ok {
  223. convertedRequest, err = adaptor.ConvertImageRequest(c, info, *imageReq)
  224. } else {
  225. return testResult{
  226. context: c,
  227. localErr: errors.New("invalid image request type"),
  228. newAPIError: types.NewError(errors.New("invalid image request type"), types.ErrorCodeConvertRequestFailed),
  229. }
  230. }
  231. case relayconstant.RelayModeRerank:
  232. // Rerank 请求 - request 已经是正确的类型
  233. if rerankReq, ok := request.(*dto.RerankRequest); ok {
  234. convertedRequest, err = adaptor.ConvertRerankRequest(c, info.RelayMode, *rerankReq)
  235. } else {
  236. return testResult{
  237. context: c,
  238. localErr: errors.New("invalid rerank request type"),
  239. newAPIError: types.NewError(errors.New("invalid rerank request type"), types.ErrorCodeConvertRequestFailed),
  240. }
  241. }
  242. case relayconstant.RelayModeResponses:
  243. // Response 请求 - request 已经是正确的类型
  244. if responseReq, ok := request.(*dto.OpenAIResponsesRequest); ok {
  245. convertedRequest, err = adaptor.ConvertOpenAIResponsesRequest(c, info, *responseReq)
  246. } else {
  247. return testResult{
  248. context: c,
  249. localErr: errors.New("invalid response request type"),
  250. newAPIError: types.NewError(errors.New("invalid response request type"), types.ErrorCodeConvertRequestFailed),
  251. }
  252. }
  253. default:
  254. // Chat/Completion 等其他请求类型
  255. if generalReq, ok := request.(*dto.GeneralOpenAIRequest); ok {
  256. convertedRequest, err = adaptor.ConvertOpenAIRequest(c, info, generalReq)
  257. } else {
  258. return testResult{
  259. context: c,
  260. localErr: errors.New("invalid general request type"),
  261. newAPIError: types.NewError(errors.New("invalid general request type"), types.ErrorCodeConvertRequestFailed),
  262. }
  263. }
  264. }
  265. if err != nil {
  266. return testResult{
  267. context: c,
  268. localErr: err,
  269. newAPIError: types.NewError(err, types.ErrorCodeConvertRequestFailed),
  270. }
  271. }
  272. jsonData, err := json.Marshal(convertedRequest)
  273. if err != nil {
  274. return testResult{
  275. context: c,
  276. localErr: err,
  277. newAPIError: types.NewError(err, types.ErrorCodeJsonMarshalFailed),
  278. }
  279. }
  280. requestBody := bytes.NewBuffer(jsonData)
  281. c.Request.Body = io.NopCloser(requestBody)
  282. resp, err := adaptor.DoRequest(c, info, requestBody)
  283. if err != nil {
  284. return testResult{
  285. context: c,
  286. localErr: err,
  287. newAPIError: types.NewOpenAIError(err, types.ErrorCodeDoRequestFailed, http.StatusInternalServerError),
  288. }
  289. }
  290. var httpResp *http.Response
  291. if resp != nil {
  292. httpResp = resp.(*http.Response)
  293. if httpResp.StatusCode != http.StatusOK {
  294. err := service.RelayErrorHandler(c.Request.Context(), httpResp, true)
  295. return testResult{
  296. context: c,
  297. localErr: err,
  298. newAPIError: types.NewOpenAIError(err, types.ErrorCodeBadResponse, http.StatusInternalServerError),
  299. }
  300. }
  301. }
  302. usageA, respErr := adaptor.DoResponse(c, httpResp, info)
  303. if respErr != nil {
  304. return testResult{
  305. context: c,
  306. localErr: respErr,
  307. newAPIError: respErr,
  308. }
  309. }
  310. if usageA == nil {
  311. return testResult{
  312. context: c,
  313. localErr: errors.New("usage is nil"),
  314. newAPIError: types.NewOpenAIError(errors.New("usage is nil"), types.ErrorCodeBadResponseBody, http.StatusInternalServerError),
  315. }
  316. }
  317. usage := usageA.(*dto.Usage)
  318. result := w.Result()
  319. respBody, err := io.ReadAll(result.Body)
  320. if err != nil {
  321. return testResult{
  322. context: c,
  323. localErr: err,
  324. newAPIError: types.NewOpenAIError(err, types.ErrorCodeReadResponseBodyFailed, http.StatusInternalServerError),
  325. }
  326. }
  327. info.PromptTokens = usage.PromptTokens
  328. quota := 0
  329. if !priceData.UsePrice {
  330. quota = usage.PromptTokens + int(math.Round(float64(usage.CompletionTokens)*priceData.CompletionRatio))
  331. quota = int(math.Round(float64(quota) * priceData.ModelRatio))
  332. if priceData.ModelRatio != 0 && quota <= 0 {
  333. quota = 1
  334. }
  335. } else {
  336. quota = int(priceData.ModelPrice * common.QuotaPerUnit)
  337. }
  338. tok := time.Now()
  339. milliseconds := tok.Sub(tik).Milliseconds()
  340. consumedTime := float64(milliseconds) / 1000.0
  341. other := service.GenerateTextOtherInfo(c, info, priceData.ModelRatio, priceData.GroupRatioInfo.GroupRatio, priceData.CompletionRatio,
  342. usage.PromptTokensDetails.CachedTokens, priceData.CacheRatio, priceData.ModelPrice, priceData.GroupRatioInfo.GroupSpecialRatio)
  343. model.RecordConsumeLog(c, 1, model.RecordConsumeLogParams{
  344. ChannelId: channel.Id,
  345. PromptTokens: usage.PromptTokens,
  346. CompletionTokens: usage.CompletionTokens,
  347. ModelName: info.OriginModelName,
  348. TokenName: "模型测试",
  349. Quota: quota,
  350. Content: "模型测试",
  351. UseTimeSeconds: int(consumedTime),
  352. IsStream: info.IsStream,
  353. Group: info.UsingGroup,
  354. Other: other,
  355. })
  356. common.SysLog(fmt.Sprintf("testing channel #%d, response: \n%s", channel.Id, string(respBody)))
  357. return testResult{
  358. context: c,
  359. localErr: nil,
  360. newAPIError: nil,
  361. }
  362. }
  363. func buildTestRequest(model string, endpointType string) dto.Request {
  364. // 根据端点类型构建不同的测试请求
  365. if endpointType != "" {
  366. switch constant.EndpointType(endpointType) {
  367. case constant.EndpointTypeEmbeddings:
  368. // 返回 EmbeddingRequest
  369. return &dto.EmbeddingRequest{
  370. Model: model,
  371. Input: []any{"hello world"},
  372. }
  373. case constant.EndpointTypeImageGeneration:
  374. // 返回 ImageRequest
  375. return &dto.ImageRequest{
  376. Model: model,
  377. Prompt: "a cute cat",
  378. N: 1,
  379. Size: "1024x1024",
  380. }
  381. case constant.EndpointTypeJinaRerank:
  382. // 返回 RerankRequest
  383. return &dto.RerankRequest{
  384. Model: model,
  385. Query: "What is Deep Learning?",
  386. Documents: []any{"Deep Learning is a subset of machine learning.", "Machine learning is a field of artificial intelligence."},
  387. TopN: 2,
  388. }
  389. case constant.EndpointTypeOpenAIResponse:
  390. // 返回 OpenAIResponsesRequest
  391. return &dto.OpenAIResponsesRequest{
  392. Model: model,
  393. Input: json.RawMessage("\"hi\""),
  394. }
  395. case constant.EndpointTypeAnthropic, constant.EndpointTypeGemini, constant.EndpointTypeOpenAI:
  396. // 返回 GeneralOpenAIRequest
  397. maxTokens := uint(10)
  398. if constant.EndpointType(endpointType) == constant.EndpointTypeGemini {
  399. maxTokens = 3000
  400. }
  401. return &dto.GeneralOpenAIRequest{
  402. Model: model,
  403. Stream: false,
  404. Messages: []dto.Message{
  405. {
  406. Role: "user",
  407. Content: "hi",
  408. },
  409. },
  410. MaxTokens: maxTokens,
  411. }
  412. }
  413. }
  414. // 自动检测逻辑(保持原有行为)
  415. // 先判断是否为 Embedding 模型
  416. if strings.Contains(strings.ToLower(model), "embedding") ||
  417. strings.HasPrefix(model, "m3e") ||
  418. strings.Contains(model, "bge-") {
  419. // 返回 EmbeddingRequest
  420. return &dto.EmbeddingRequest{
  421. Model: model,
  422. Input: []any{"hello world"},
  423. }
  424. }
  425. // Chat/Completion 请求 - 返回 GeneralOpenAIRequest
  426. testRequest := &dto.GeneralOpenAIRequest{
  427. Model: model,
  428. Stream: false,
  429. Messages: []dto.Message{
  430. {
  431. Role: "user",
  432. Content: "hi",
  433. },
  434. },
  435. }
  436. if strings.HasPrefix(model, "o") {
  437. testRequest.MaxCompletionTokens = 10
  438. } else if strings.Contains(model, "thinking") {
  439. if !strings.Contains(model, "claude") {
  440. testRequest.MaxTokens = 50
  441. }
  442. } else if strings.Contains(model, "gemini") {
  443. testRequest.MaxTokens = 3000
  444. } else {
  445. testRequest.MaxTokens = 10
  446. }
  447. return testRequest
  448. }
  449. func TestChannel(c *gin.Context) {
  450. channelId, err := strconv.Atoi(c.Param("id"))
  451. if err != nil {
  452. common.ApiError(c, err)
  453. return
  454. }
  455. channel, err := model.CacheGetChannel(channelId)
  456. if err != nil {
  457. channel, err = model.GetChannelById(channelId, true)
  458. if err != nil {
  459. common.ApiError(c, err)
  460. return
  461. }
  462. }
  463. //defer func() {
  464. // if channel.ChannelInfo.IsMultiKey {
  465. // go func() { _ = channel.SaveChannelInfo() }()
  466. // }
  467. //}()
  468. testModel := c.Query("model")
  469. endpointType := c.Query("endpoint_type")
  470. tik := time.Now()
  471. result := testChannel(channel, testModel, endpointType)
  472. if result.localErr != nil {
  473. c.JSON(http.StatusOK, gin.H{
  474. "success": false,
  475. "message": result.localErr.Error(),
  476. "time": 0.0,
  477. })
  478. return
  479. }
  480. tok := time.Now()
  481. milliseconds := tok.Sub(tik).Milliseconds()
  482. go channel.UpdateResponseTime(milliseconds)
  483. consumedTime := float64(milliseconds) / 1000.0
  484. if result.newAPIError != nil {
  485. c.JSON(http.StatusOK, gin.H{
  486. "success": false,
  487. "message": result.newAPIError.Error(),
  488. "time": consumedTime,
  489. })
  490. return
  491. }
  492. c.JSON(http.StatusOK, gin.H{
  493. "success": true,
  494. "message": "",
  495. "time": consumedTime,
  496. })
  497. }
  498. var testAllChannelsLock sync.Mutex
  499. var testAllChannelsRunning bool = false
  500. func testAllChannels(notify bool) error {
  501. testAllChannelsLock.Lock()
  502. if testAllChannelsRunning {
  503. testAllChannelsLock.Unlock()
  504. return errors.New("测试已在运行中")
  505. }
  506. testAllChannelsRunning = true
  507. testAllChannelsLock.Unlock()
  508. channels, getChannelErr := model.GetAllChannels(0, 0, true, false)
  509. if getChannelErr != nil {
  510. return getChannelErr
  511. }
  512. var disableThreshold = int64(common.ChannelDisableThreshold * 1000)
  513. if disableThreshold == 0 {
  514. disableThreshold = 10000000 // a impossible value
  515. }
  516. gopool.Go(func() {
  517. // 使用 defer 确保无论如何都会重置运行状态,防止死锁
  518. defer func() {
  519. testAllChannelsLock.Lock()
  520. testAllChannelsRunning = false
  521. testAllChannelsLock.Unlock()
  522. }()
  523. for _, channel := range channels {
  524. isChannelEnabled := channel.Status == common.ChannelStatusEnabled
  525. tik := time.Now()
  526. result := testChannel(channel, "", "")
  527. tok := time.Now()
  528. milliseconds := tok.Sub(tik).Milliseconds()
  529. shouldBanChannel := false
  530. newAPIError := result.newAPIError
  531. // request error disables the channel
  532. if newAPIError != nil {
  533. shouldBanChannel = service.ShouldDisableChannel(channel.Type, result.newAPIError)
  534. }
  535. // 当错误检查通过,才检查响应时间
  536. if common.AutomaticDisableChannelEnabled && !shouldBanChannel {
  537. if milliseconds > disableThreshold {
  538. err := fmt.Errorf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0)
  539. newAPIError = types.NewOpenAIError(err, types.ErrorCodeChannelResponseTimeExceeded, http.StatusRequestTimeout)
  540. shouldBanChannel = true
  541. }
  542. }
  543. // disable channel
  544. if isChannelEnabled && shouldBanChannel && channel.GetAutoBan() {
  545. processChannelError(result.context, *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, common.GetContextKeyString(result.context, constant.ContextKeyChannelKey), channel.GetAutoBan()), newAPIError)
  546. }
  547. // enable channel
  548. if !isChannelEnabled && service.ShouldEnableChannel(newAPIError, channel.Status) {
  549. service.EnableChannel(channel.Id, common.GetContextKeyString(result.context, constant.ContextKeyChannelKey), channel.Name)
  550. }
  551. channel.UpdateResponseTime(milliseconds)
  552. time.Sleep(common.RequestInterval)
  553. }
  554. if notify {
  555. service.NotifyRootUser(dto.NotifyTypeChannelTest, "通道测试完成", "所有通道测试已完成")
  556. }
  557. })
  558. return nil
  559. }
  560. func TestAllChannels(c *gin.Context) {
  561. err := testAllChannels(true)
  562. if err != nil {
  563. common.ApiError(c, err)
  564. return
  565. }
  566. c.JSON(http.StatusOK, gin.H{
  567. "success": true,
  568. "message": "",
  569. })
  570. }
  571. var autoTestChannelsOnce sync.Once
  572. func AutomaticallyTestChannels() {
  573. autoTestChannelsOnce.Do(func() {
  574. for {
  575. if !operation_setting.GetMonitorSetting().AutoTestChannelEnabled {
  576. time.Sleep(10 * time.Minute)
  577. continue
  578. }
  579. frequency := operation_setting.GetMonitorSetting().AutoTestChannelMinutes
  580. common.SysLog(fmt.Sprintf("automatically test channels with interval %d minutes", frequency))
  581. for {
  582. time.Sleep(time.Duration(frequency) * time.Minute)
  583. common.SysLog("automatically testing all channels")
  584. _ = testAllChannels(false)
  585. common.SysLog("automatically channel test finished")
  586. if !operation_setting.GetMonitorSetting().AutoTestChannelEnabled {
  587. break
  588. }
  589. }
  590. }
  591. })
  592. }