channel-test.go 19 KB

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