channel_cache.go 7.7 KB

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