This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
/
util.go
83 lines (71 loc) · 2.37 KB
/
util.go
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package bigtable
import (
"context"
"fmt"
"cloud.google.com/go/bigtable"
log "github.com/sirupsen/logrus"
)
func EnsureTableExists(ctx context.Context, createCf bool, client *bigtable.AdminClient, tableName string, columnFamilies map[string]bigtable.GCPolicy) error {
tables, err := client.Tables(ctx)
if err != nil {
log.Errorf("bt-ensure-table-exists: failed to list tables: %s", err)
return err
}
found := false
for _, t := range tables {
if t == tableName {
found = true
break
}
}
if !found {
if !createCf {
return fmt.Errorf("table %q does not exist and creation of tables is disabled", tableName)
}
log.Infof("bt-ensure-table-exists: table %q does not yet exist. Creating it.", tableName)
table := bigtable.TableConf{
TableID: tableName,
Families: columnFamilies,
}
err := client.CreateTableFromConf(ctx, &table)
if err != nil {
log.Errorf("bt-ensure-table-exists: failed to create table %q: %s", tableName, err)
}
return err
}
log.Infof("bt-ensure-table-exists: table %q exists.", tableName)
// table exists. Lets make sure that it has all of the CF's we need.
table, err := client.TableInfo(ctx, tableName)
if err != nil {
log.Errorf("bt-ensure-table-exists: failed to get tableInfo of %q: %s", tableName, err)
return err
}
existingFamilies := make(map[string]string)
for _, cf := range table.FamilyInfos {
existingFamilies[cf.Name] = cf.GCPolicy
}
for cfName, wantPolicy := range columnFamilies {
havePolicy, ok := existingFamilies[cfName]
if !ok {
log.Infof("bt-ensure-table-exists: column family %s/%s does not exist. Creating it.", tableName, cfName)
err = client.CreateColumnFamily(ctx, tableName, cfName)
if err != nil {
log.Errorf("bt-ensure-table-exists: failed to create cf %s/%s: %s", tableName, cfName, err)
return err
}
err = client.SetGCPolicy(ctx, tableName, cfName, wantPolicy)
if err != nil {
log.Errorf("bt-ensure-table-exists: failed to set GCPolicy of %s/%s: %s", tableName, cfName, err)
return err
}
} else if havePolicy == "" {
log.Infof("bt-ensure-table-exists: column family %s/%s exists but has no GCPolicy. Creating it.", tableName, cfName)
err = client.SetGCPolicy(ctx, tableName, cfName, wantPolicy)
if err != nil {
log.Errorf("bt-ensure-table-exists: failed to set GCPolicy of %s/%s: %s", tableName, cfName, err)
return err
}
}
}
return nil
}