channel_cache.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/rand"
  6. "one-api/common"
  7. "one-api/constant"
  8. "one-api/logger"
  9. "one-api/setting"
  10. "one-api/setting/ratio_setting"
  11. "sort"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/gin-gonic/gin"
  16. )
  17. var group2model2channels map[string]map[string][]int // enabled channel
  18. var channelsIDM map[int]*Channel // all channels include disabled
  19. var channelSyncLock sync.RWMutex
  20. func InitChannelCache() {
  21. if !common.MemoryCacheEnabled {
  22. return
  23. }
  24. newChannelId2channel := make(map[int]*Channel)
  25. var channels []*Channel
  26. DB.Find(&channels)
  27. for _, channel := range channels {
  28. newChannelId2channel[channel.Id] = channel
  29. }
  30. var abilities []*Ability
  31. DB.Find(&abilities)
  32. groups := make(map[string]bool)
  33. for _, ability := range abilities {
  34. groups[ability.Group] = true
  35. }
  36. newGroup2model2channels := make(map[string]map[string][]int)
  37. for group := range groups {
  38. newGroup2model2channels[group] = make(map[string][]int)
  39. }
  40. for _, channel := range channels {
  41. if channel.Status != common.ChannelStatusEnabled {
  42. continue // skip disabled channels
  43. }
  44. groups := strings.Split(channel.Group, ",")
  45. for _, group := range groups {
  46. models := strings.Split(channel.Models, ",")
  47. for _, model := range models {
  48. if _, ok := newGroup2model2channels[group][model]; !ok {
  49. newGroup2model2channels[group][model] = make([]int, 0)
  50. }
  51. newGroup2model2channels[group][model] = append(newGroup2model2channels[group][model], channel.Id)
  52. }
  53. }
  54. }
  55. // sort by priority
  56. for group, model2channels := range newGroup2model2channels {
  57. for model, channels := range model2channels {
  58. sort.Slice(channels, func(i, j int) bool {
  59. return newChannelId2channel[channels[i]].GetPriority() > newChannelId2channel[channels[j]].GetPriority()
  60. })
  61. newGroup2model2channels[group][model] = channels
  62. }
  63. }
  64. channelSyncLock.Lock()
  65. group2model2channels = newGroup2model2channels
  66. //channelsIDM = newChannelId2channel
  67. for i, channel := range newChannelId2channel {
  68. if channel.ChannelInfo.IsMultiKey {
  69. channel.Keys = channel.GetKeys()
  70. if channel.ChannelInfo.MultiKeyMode == constant.MultiKeyModePolling {
  71. if oldChannel, ok := channelsIDM[i]; ok {
  72. // 存在旧的渠道,如果是多key且轮询,保留轮询索引信息
  73. if oldChannel.ChannelInfo.IsMultiKey && oldChannel.ChannelInfo.MultiKeyMode == constant.MultiKeyModePolling {
  74. channel.ChannelInfo.MultiKeyPollingIndex = oldChannel.ChannelInfo.MultiKeyPollingIndex
  75. }
  76. }
  77. }
  78. }
  79. }
  80. channelsIDM = newChannelId2channel
  81. channelSyncLock.Unlock()
  82. logger.SysLog("channels synced from database")
  83. }
  84. func SyncChannelCache(frequency int) {
  85. for {
  86. time.Sleep(time.Duration(frequency) * time.Second)
  87. logger.SysLog("syncing channels from database")
  88. InitChannelCache()
  89. }
  90. }
  91. func CacheGetRandomSatisfiedChannel(c *gin.Context, group string, model string, retry int) (*Channel, string, error) {
  92. var channel *Channel
  93. var err error
  94. selectGroup := group
  95. if group == "auto" {
  96. if len(setting.AutoGroups) == 0 {
  97. return nil, selectGroup, errors.New("auto groups is not enabled")
  98. }
  99. for _, autoGroup := range setting.AutoGroups {
  100. if common.DebugEnabled {
  101. println("autoGroup:", autoGroup)
  102. }
  103. channel, _ = getRandomSatisfiedChannel(autoGroup, model, retry)
  104. if channel == nil {
  105. continue
  106. } else {
  107. c.Set("auto_group", autoGroup)
  108. selectGroup = autoGroup
  109. if common.DebugEnabled {
  110. println("selectGroup:", selectGroup)
  111. }
  112. break
  113. }
  114. }
  115. } else {
  116. channel, err = getRandomSatisfiedChannel(group, model, retry)
  117. if err != nil {
  118. return nil, group, err
  119. }
  120. }
  121. return channel, selectGroup, nil
  122. }
  123. func getRandomSatisfiedChannel(group string, model string, retry int) (*Channel, error) {
  124. // if memory cache is disabled, get channel directly from database
  125. if !common.MemoryCacheEnabled {
  126. return GetRandomSatisfiedChannel(group, model, retry)
  127. }
  128. channelSyncLock.RLock()
  129. defer channelSyncLock.RUnlock()
  130. // First, try to find channels with the exact model name.
  131. channels := group2model2channels[group][model]
  132. // If no channels found, try to find channels with the normalized model name.
  133. if len(channels) == 0 {
  134. normalizedModel := ratio_setting.FormatMatchingModelName(model)
  135. channels = group2model2channels[group][normalizedModel]
  136. }
  137. if len(channels) == 0 {
  138. return nil, nil
  139. }
  140. if len(channels) == 1 {
  141. if channel, ok := channelsIDM[channels[0]]; ok {
  142. return channel, nil
  143. }
  144. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channels[0])
  145. }
  146. uniquePriorities := make(map[int]bool)
  147. for _, channelId := range channels {
  148. if channel, ok := channelsIDM[channelId]; ok {
  149. uniquePriorities[int(channel.GetPriority())] = true
  150. } else {
  151. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  152. }
  153. }
  154. var sortedUniquePriorities []int
  155. for priority := range uniquePriorities {
  156. sortedUniquePriorities = append(sortedUniquePriorities, priority)
  157. }
  158. sort.Sort(sort.Reverse(sort.IntSlice(sortedUniquePriorities)))
  159. if retry >= len(uniquePriorities) {
  160. retry = len(uniquePriorities) - 1
  161. }
  162. targetPriority := int64(sortedUniquePriorities[retry])
  163. // get the priority for the given retry number
  164. var targetChannels []*Channel
  165. for _, channelId := range channels {
  166. if channel, ok := channelsIDM[channelId]; ok {
  167. if channel.GetPriority() == targetPriority {
  168. targetChannels = append(targetChannels, channel)
  169. }
  170. } else {
  171. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  172. }
  173. }
  174. // 平滑系数
  175. smoothingFactor := 10
  176. // Calculate the total weight of all channels up to endIdx
  177. totalWeight := 0
  178. for _, channel := range targetChannels {
  179. totalWeight += channel.GetWeight() + smoothingFactor
  180. }
  181. // Generate a random value in the range [0, totalWeight)
  182. randomWeight := rand.Intn(totalWeight)
  183. // Find a channel based on its weight
  184. for _, channel := range targetChannels {
  185. randomWeight -= channel.GetWeight() + smoothingFactor
  186. if randomWeight < 0 {
  187. return channel, nil
  188. }
  189. }
  190. // return null if no channel is not found
  191. return nil, errors.New("channel not found")
  192. }
  193. func CacheGetChannel(id int) (*Channel, error) {
  194. if !common.MemoryCacheEnabled {
  195. return GetChannelById(id, true)
  196. }
  197. channelSyncLock.RLock()
  198. defer channelSyncLock.RUnlock()
  199. c, ok := channelsIDM[id]
  200. if !ok {
  201. return nil, fmt.Errorf("渠道# %d,已不存在", id)
  202. }
  203. return c, nil
  204. }
  205. func CacheGetChannelInfo(id int) (*ChannelInfo, error) {
  206. if !common.MemoryCacheEnabled {
  207. channel, err := GetChannelById(id, true)
  208. if err != nil {
  209. return nil, err
  210. }
  211. return &channel.ChannelInfo, nil
  212. }
  213. channelSyncLock.RLock()
  214. defer channelSyncLock.RUnlock()
  215. c, ok := channelsIDM[id]
  216. if !ok {
  217. return nil, fmt.Errorf("渠道# %d,已不存在", id)
  218. }
  219. return &c.ChannelInfo, nil
  220. }
  221. func CacheUpdateChannelStatus(id int, status int) {
  222. if !common.MemoryCacheEnabled {
  223. return
  224. }
  225. channelSyncLock.Lock()
  226. defer channelSyncLock.Unlock()
  227. if channel, ok := channelsIDM[id]; ok {
  228. channel.Status = status
  229. }
  230. if status != common.ChannelStatusEnabled {
  231. // delete the channel from group2model2channels
  232. for group, model2channels := range group2model2channels {
  233. for model, channels := range model2channels {
  234. for i, channelId := range channels {
  235. if channelId == id {
  236. // remove the channel from the slice
  237. group2model2channels[group][model] = append(channels[:i], channels[i+1:]...)
  238. break
  239. }
  240. }
  241. }
  242. }
  243. }
  244. }
  245. func CacheUpdateChannel(channel *Channel) {
  246. if !common.MemoryCacheEnabled {
  247. return
  248. }
  249. channelSyncLock.Lock()
  250. defer channelSyncLock.Unlock()
  251. if channel == nil {
  252. return
  253. }
  254. println("CacheUpdateChannel:", channel.Id, channel.Name, channel.Status, channel.ChannelInfo.MultiKeyPollingIndex)
  255. println("before:", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  256. channelsIDM[channel.Id] = channel
  257. println("after :", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  258. }