|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + |
| 6 | + "github.com/astaxie/beego/migration" |
| 7 | + "github.com/astaxie/beego/orm" |
| 8 | + |
| 9 | + "github.com/Qihoo360/wayne/src/backend/models" |
| 10 | + "github.com/Qihoo360/wayne/src/backend/util/logs" |
| 11 | +) |
| 12 | + |
| 13 | +const ( |
| 14 | + UpSQL = "ALTER TABLE `namespace` ADD COLUMN `kube_namespace` VARCHAR(128) NOT NULL DEFAULT '' AFTER `deleted`, ADD INDEX `namespace_kube_namespace` (`kube_namespace` ASC);" |
| 15 | + DownSql = "ALTER TABLE `wayne_dev`.`namespace` DROP COLUMN `kube_namespace`, DROP INDEX `namespace_kube_namespace` ;" |
| 16 | +) |
| 17 | + |
| 18 | +type NamespaceMetaData struct { |
| 19 | + // kubernetes' namespace |
| 20 | + Namespace string `json:"namespace,omitempty"` |
| 21 | +} |
| 22 | + |
| 23 | +// DO NOT MODIFY |
| 24 | +type V16_20190312_154209 struct { |
| 25 | + migration.Migration |
| 26 | +} |
| 27 | + |
| 28 | +// DO NOT MODIFY |
| 29 | +func init() { |
| 30 | + m := &V16_20190312_154209{} |
| 31 | + m.Created = "20190312_154209" |
| 32 | + |
| 33 | + migration.Register("V16_20190312_154209", m) |
| 34 | +} |
| 35 | + |
| 36 | +// Run the migrations |
| 37 | +func (m *V16_20190312_154209) Up() { |
| 38 | + // For migration namespace metadata namespace to kubeNamespace |
| 39 | + o := orm.NewOrm() |
| 40 | + _, err := o.Raw(UpSQL).Exec() |
| 41 | + if err != nil { |
| 42 | + logs.Error("Exec UpSQL error.", UpSQL, err) |
| 43 | + return |
| 44 | + } |
| 45 | + |
| 46 | + namespaces := []*models.Namespace{} |
| 47 | + _, err = o.QueryTable(new(models.Namespace)). |
| 48 | + All(&namespaces) |
| 49 | + if err != nil { |
| 50 | + logs.Error("Get all namespaces error.", err) |
| 51 | + return |
| 52 | + } |
| 53 | + for _, namespace := range namespaces { |
| 54 | + if namespace.MetaData != "" { |
| 55 | + metadata := &NamespaceMetaData{} |
| 56 | + err := json.Unmarshal([]byte(namespace.MetaData), metadata) |
| 57 | + if err != nil { |
| 58 | + logs.Error("json.Unmarshal namespaces error.", namespace, err) |
| 59 | + continue |
| 60 | + } |
| 61 | + if metadata.Namespace != "" { |
| 62 | + namespace.KubeNamespace = metadata.Namespace |
| 63 | + _, err := o.Update(namespace) |
| 64 | + if err != nil { |
| 65 | + logs.Error("update namespaces error.", namespace, err) |
| 66 | + continue |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + // use m.SQL("CREATE TABLE ...") to make schema update |
| 73 | + |
| 74 | +} |
| 75 | + |
| 76 | +// Reverse the migrations |
| 77 | +func (m *V16_20190312_154209) Down() { |
| 78 | + // use m.SQL("DROP TABLE ...") to reverse schema update |
| 79 | + m.SQL(DownSql) |
| 80 | + |
| 81 | +} |
0 commit comments