channel-test.go 20 KB

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