惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
GbyAI
GbyAI
SecWiki News
SecWiki News
Project Zero
Project Zero
C
Cisco Blogs
Simon Willison's Weblog
Simon Willison's Weblog
P
Privacy International News Feed
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Scott Helme
Scott Helme
A
Arctic Wolf
Security Latest
Security Latest
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law Blog
Apple Machine Learning Research
Apple Machine Learning Research
T
Tailwind CSS Blog
The Hacker News
The Hacker News
T
Tenable Blog
雷峰网
雷峰网
有赞技术团队
有赞技术团队
V
V2EX
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Threat Research - Cisco Blogs
T
Threatpost
AWS News Blog
AWS News Blog
L
LINUX DO - 热门话题
Application and Cybersecurity Blog
Application and Cybersecurity Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
S
SegmentFault 最新的问题
月光博客
月光博客
Spread Privacy
Spread Privacy
S
Secure Thoughts
宝玉的分享
宝玉的分享
博客园 - 三生石上(FineUI控件)
Forbes - Security
Forbes - Security
T
The Exploit Database - CXSecurity.com
G
GRAHAM CLULEY
The Last Watchdog
The Last Watchdog
Y
Y Combinator Blog
I
Intezer
博客园 - 【当耐特】
B
Blog RSS Feed
Attack and Defense Labs
Attack and Defense Labs
I
InfoQ
博客园 - 叶小钗
Cyberwarzone
Cyberwarzone
V2EX - 技术
V2EX - 技术
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Hugging Face - Blog
Hugging Face - Blog
H
Help Net Security
C
CERT Recently Published Vulnerability Notes

Mohuishou

如何实现支持多集群的 Kubernetes Operator? 第三方应用如何调用我们 kubebuilder 生成的自定义资源? Kubernetes 简明教程 k8s job 为何迟迟不能结束? Go 工程化(十一) 如何优雅的写出 repo 层代码 Go 工程化(十) 如何在整洁架构中使用事务? 给博客添加章节目录 使用 Notion Database 管理静态博客文章 一个普通 Go 开发的三年 4. localhost 就一定是 localhost 么? Go可用性(七) 总结: 一张图串联可用性知识点 Go可用性(六) 熔断 10. 总结 9. kubebuilder 进阶: 源码分析 8. kubebuilder 进阶: webhook 7. kubebuilder 进阶: 测试 6. kubebuilder 实战: status & event 5. kubebuilder 实战: CRUD 4. kustomize 简明教程 3. KubeBuilder 简明教程 2. Kind: 如何快速搭建本地 K8s 开发环境? 1. Operator概述: 如何对 Kubernetes 进行扩展 Go可用性(五) 自适应限流 Go可用性(四) 漏桶算法 Go可用性(三) 令牌桶的实现 rate/limt Go可用性(二) 令牌桶原理及使用 Go可用性(一) 隔离设计 Go并发编程(十二) Singleflight Go工程化(九) 项目重构实践 Go工程化(八) 单元测试 Go工程化(七) Go Module Go工程化(六) 配置管理 Go工程化(五) API 设计下: 基于 protobuf 自动生成 gin 代码 Go工程化(四) API 设计上: 项目结构 & 设计 Go工程化(三) 依赖注入框架 wire Go工程化(二) 项目目录结构 Go工程化(一) 架构整洁之道阅读笔记 Go并发编程(十一) 总结 Go并发编程(十) 深入理解 Channel Go并发编程(九) 深入理解 Context Go并发编程(八) 深入理解 sync.Once Go并发编程(七) 深入理解 errgroup Go并发编程(六) 深入理解 WaitGroup Go并发编程(五) 深入理解 sync/atomic Go并发编程(四) 深入理解 Mutex Go并发编程(三) data race Go并发编程(二) Go 内存模型 Go并发编程(一) goroutine Go错误处理最佳实践 微服务(二) 服务发现&多租户 微服务(一) 微服务概览 5. 栈下: 深入理解 defer 4. 栈上: 如何实现一个计算器 Go Struct 初始化风格的抉择 3. 数组下: 使用 GDB 调试 Golang 代码 2. 数组上: 深入理解 slice 1. 链表: 深入理解container/list&LRU缓存的实现 Go设计模式24-总结(更新完毕) Go设计模式23-中介模式 Go设计模式22-解释器模式 Go设计模式21-命令模式 Go设计模式20-备忘录模式 Go设计模式19-访问者模式 Go设计模式18-迭代器模式 Go设计模式17-状态模式 Go设计模式16-职责链模式(Gin的中间件实现) Go设计模式15-策略模式 Go模板模式14-模板模式 Go设计模式13-观察者模式(实现简单的EventBus) Go设计模式12-享元模式 Go设计模式11-组合模式 Go设计模式10-门面模式 Go设计模式09-适配器模式 Go设计模式08-装饰器模式 Go设计模式07-桥接模式 Go设计模式06-代理模式(generate实现类似动态代理) Go设计模式05-创建型模式总结 Go设计模式04-原型模式 Go设计模式03-建造者模式 Go设计模式02-工厂模式&DI容器 笔记-让你最快速地改善代码质量的20条编程规范 Go设计模式01-单例模式 一点拙见-如何写好一个技术预研报告? Go Web小技巧(四)在单个仓库中支持多个 go mod 模块 Go Web 小技巧(三)Gin 参数绑定 Go Web 小技巧(二)GORM 使用自定义类型 Go Web 小技巧(一)简化Gin接口代码 善用工具之postman高级用法概述 go generate and ast hexo-next-algolia-search全文搜索 docker镜像瘦身&优化 GORM避坑指南之含关联关系的更新 Github Actions介绍&自动构建Github Pages博客 在blog中内嵌在线PPT 记一次net http内存泄漏 使用TravisCI自动部署Blog 使用Goland调试Go程序 Httprouter介绍及源码阅读 Gin源码阅读 从0.1开始
一个十分边缘的gorm的bug
Mohuishou · 2018-09-21 · via Mohuishou

注:本文已发布超过一年,请注意您所使用工具的相关版本是否适用

[toc]

复现代码

这个代码的触发条件比较严苛,首先必须要保证 gorm 执行的一行必须为updates语句,并且在updates(struct),并且传入的这个struct必须要包含一个直接或者间接关联的一个多态表,这些条件缺一不可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
type A struct {
gorm.Model
Name string
B B `gorm:"polymorphic:Owner"`
}

type B struct {
gorm.Model
OwnerID uint
OwnerType string
}

a := A{Name: "test"}
db = db.Model(&a)
db.Where(a)
db.Updates(A{Name: "test2"}) // panic

现象

先说现象,在一次代码联调的过程当中,发现调用一个更新接口的时候会报 500 错误(panic),但是在什么都不修改的情况下,再次调用接口,更新成功

错误日志如下,是由于一个空指针的调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
panic: runtime error: invalid memory address or nil pointer dereference

github.com/jinzhu/gorm.(*DB).clone(0x0, 0x0)
E:/SoftFile/GOPATH/src/github.com/jinzhu/gorm/main.go:715 +0x4e
github.com/jinzhu/gorm.(*DB).Model(0x0, 0x6cb460, 0xc00017c160, 0x0)
E:/SoftFile/GOPATH/src/github.com/jinzhu/gorm/main.go:445 +0x32
github.com/jinzhu/gorm.(*Scope).TableName(0xc000172100, 0xc00016c3c0, 0x6f894a)
E:/SoftFile/GOPATH/src/github.com/jinzhu/gorm/scope.go:325 +0x133
github.com/jinzhu/gorm.(*Scope).GetModelStruct.func2(0xc000170010, 0xc000172100, 0xc00017a050, 0xc0001749c0)
E:/SoftFile/GOPATH/src/github.com/jinzhu/gorm/model_struct.go:420 +0x24c7
github.com/jinzhu/gorm.(*Scope).GetModelStruct(0xc000172100, 0xc00017a050)
E:/SoftFile/GOPATH/src/github.com/jinzhu/gorm/model_struct.go:574 +0x140c
github.com/jinzhu/gorm.(*Scope).Fields(0xc000172100, 0xc000172100, 0x2030000, 0x2030000)
E:/SoftFile/GOPATH/src/github.com/jinzhu/gorm/scope.go:115 +0xaf
github.com/jinzhu/gorm.convertInterfaceToMap(0x6cb460, 0xc00017c160, 0xc00017c001, 0x199)
E:/SoftFile/GOPATH/src/github.com/jinzhu/gorm/scope.go:860 +0x4f8
github.com/jinzhu/gorm.(*Scope).updatedAttrsWithValues(0xc000172080, 0x6cb460, 0xc00017c160, 0x6cb460, 0xc00017c160)
E:/SoftFile/GOPATH/src/github.com/jinzhu/gorm/scope.go:877 +0x8b
github.com/jinzhu/gorm.assignUpdatingAttributesCallback(0xc000172080)
E:/SoftFile/GOPATH/src/github.com/jinzhu/gorm/callback_update.go:25 +0x81
github.com/jinzhu/gorm.(*Scope).callCallbacks(0xc000172080, 0xc00012ff00, 0x9, 0x10, 0xc00017c160)
E:/SoftFile/GOPATH/src/github.com/jinzhu/gorm/scope.go:831 +0x5c
github.com/jinzhu/gorm.(*DB).Updates(0xc00017e090, 0x6cb460, 0xc00017c160, 0x0, 0x0, 0x0, 0xc00017e090)
E:/SoftFile/GOPATH/src/github.com/jinzhu/gorm/main.go:383 +0x13b
main.main()
E:/SoftFile/GOPATH/src/github.com/mohuishou/test/main.go:34 +0x269

调试

首先从 panic 的堆栈顶端往下看, 是调用s.db的时候报的错,推断应该是s的值为nil导致的错误

1
2
3
4
5
func (s *DB) clone() *DB {
db := &DB{
db: s.db, // 从这一行开始panic
}
}

接着往下看,这里的s应该也是一个nil

1
2
3
4
5
6
7
8
9
10
// Model specify the model you would like to run db operations
// // update all users's name to `hello`
// db.Model(&User{}).Update("name", "hello")
// // if user's primary key is non-blank, will use it as condition, then will only update the user's name to `hello`
// db.Model(&user).Update("name", "hello")
func (s *DB) Model(value interface{}) *DB {
c := s.clone() // 从这里调用
c.Value = value
return c
}

接着走, 在获取表名的时候,需要调用scope.db.Model, 这里的 db 应该是一个nil导致调用失败

1
2
3
4
5
// TableName return table name
func (scope *Scope) TableName() string {
// ...
return scope.GetModelStruct().TableName(scope.db.Model(scope.Value))
}

从下面的调用,可以看到,实在获取Struct的结构的时候,由于有多态关联(polymorphic)的 tag,所以需要获取多态表的TableName

1
2
3
4
5
6
7
8
9
10
11
func (scope *Scope) GetModelStruct() *ModelStruct {
// ...
if polymorphic := field.TagSettings["POLYMORPHIC"]; polymorphic != "" {
if value, ok := field.TagSettings["POLYMORPHIC_VALUE"]; ok {
relationship.PolymorphicValue = value
} else {
// 这里调用
relationship.PolymorphicValue = scope.TableName()
}
}
}

调用GetModelStruct的原因是因为需要获取value的所有字段,字段等于 nil 的时候,就会调用GetModelStruct去获取

1
2
3
4
5
6
7
8
9
// Fields get value's fields
func (scope *Scope) Fields() []*Field {
if scope.fields == nil {
// ...
for _, structField := range scope.GetModelStruct().StructFields {
// ...
}
}
}

看这个函数可以发现,会把interface转为map, 由于我们最开始传入的是db.Updates(A{Name: "test2"})条件是一个 struct 所以会执行下面case interface{} -> default分支。此时会调用(&Scope{Value: values}).Fields(),这时候可以发现Scope这个对象在初始话的时候是没有db这个字段的,所以在获取 table name 的时候需要调用到scope.db这时候就会 panic

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
func convertInterfaceToMap(values interface{}, withIgnoredField bool) map[string]interface{} {
var attrs = map[string]interface{}{}

switch value := values.(type) {
case map[string]interface{}:
return value
case []interface{}:
for _, v := range value {
for key, value := range convertInterfaceToMap(v, withIgnoredField) {
attrs[key] = value
}
}
case interface{}:
reflectValue := reflect.ValueOf(values)

switch reflectValue.Kind() {
case reflect.Map:
for _, key := range reflectValue.MapKeys() {
attrs[ToDBName(key.Interface().(string))] = reflectValue.MapIndex(key).Interface()
}
default:
// 在这里调用
for _, field := range (&Scope{Value: values}).Fields() {
if !field.IsBlank && (withIgnoredField || !field.IsIgnored) {
attrs[field.DBName] = field.Field.Interface()
}
}
}
}
return attrs
}

到这里这个 bug 就算结案了,但是接着看看,为什么会调用这个函数.

这个函数会获取需要更新的字段map,如果传入的是一个struct,会转换为map

1
2
3
4
5
6
7
8
9
func (scope *Scope) updatedAttrsWithValues(value interface{}) (results map[string]interface{}, hasUpdate bool) {
if scope.IndirectValue().Kind() != reflect.Struct {
return convertInterfaceToMap(value, false), true
}

results = map[string]interface{}{}

for key, value := range convertInterfaceToMap(value, true) {}
}

这个方法会把获取到需要更新的 map 保存下来

1
2
3
4
5
6
7
8
9
10
// assignUpdatingAttributesCallback assign updating attributes to model
func assignUpdatingAttributesCallback(scope *Scope) {
if attrs, ok := scope.InstanceGet("gorm:update_interface"); ok {
if updateMaps, hasUpdate := scope.updatedAttrsWithValues(attrs); hasUpdate {
scope.InstanceSet("gorm:update_attrs", updateMaps)
} else {
scope.SkipLeft()
}
}
}

解决方案

https://github.com/jinzhu/gorm/pull/2105

总结

GORM,使用 map 而不是 struct

在使用的 GORM 的时候,需要更新一些字段的时候最好使用 map 而不是 struct,因为如果使用 struct,gorm 最终会把这个 struct 转换为 map,并且如果这个 struct 包含一些关联关系,gorm 会一直递归的查找转换下去,如果整个表的关联关系比较复杂,会导致效率比较低下

为什么不需要修改代码,第二次运行就不会 panic

这是由于 GORM 会对 struct 的结构有一个全局的缓存modelStructsMap,由于这个是因为查找关联关系的时候报错,其本身已经新建了一个modelstruct并且缓存了下来,所以再次调用的时候就不会执行后面的代码了

1
2
3
4
5
6
7
8
9
// GetModelStruct get value's model struct, relationships based on struct and tag definition
func (scope *Scope) GetModelStruct() *ModelStruct {
//...
// Get Cached model struct
if value := modelStructsMap.Get(reflectType); value != nil {
return value
}
// ...
}

调试总结

调试的过程比写来的要艰辛很多,由于调试的时候是从自身的代码开始,通过Goland的 debug 不断的打断点,一遍一遍的执行,查找整个执行的过程,导致忽略了最直接找到错误代码的方式。

不过这也是一个宝贵的经历,这个 Bug 调试结束之后,Goland强大的调试功能已经可以玩的比较 6 了

关注我获取更新

猜你喜欢