You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1093 lines
36 KiB

  1. /*
  2. Copyright 2015 Google LLC
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package bigtable
  14. import (
  15. "errors"
  16. "fmt"
  17. "math"
  18. "regexp"
  19. "strings"
  20. "time"
  21. "cloud.google.com/go/bigtable/internal/gax"
  22. btopt "cloud.google.com/go/bigtable/internal/option"
  23. "cloud.google.com/go/iam"
  24. "cloud.google.com/go/internal/optional"
  25. "cloud.google.com/go/longrunning"
  26. lroauto "cloud.google.com/go/longrunning/autogen"
  27. "github.com/golang/protobuf/ptypes"
  28. durpb "github.com/golang/protobuf/ptypes/duration"
  29. "golang.org/x/net/context"
  30. "google.golang.org/api/cloudresourcemanager/v1"
  31. "google.golang.org/api/iterator"
  32. "google.golang.org/api/option"
  33. gtransport "google.golang.org/api/transport/grpc"
  34. btapb "google.golang.org/genproto/googleapis/bigtable/admin/v2"
  35. "google.golang.org/genproto/protobuf/field_mask"
  36. "google.golang.org/grpc"
  37. "google.golang.org/grpc/codes"
  38. "google.golang.org/grpc/metadata"
  39. "google.golang.org/grpc/status"
  40. )
  41. const adminAddr = "bigtableadmin.googleapis.com:443"
  42. // AdminClient is a client type for performing admin operations within a specific instance.
  43. type AdminClient struct {
  44. conn *grpc.ClientConn
  45. tClient btapb.BigtableTableAdminClient
  46. lroClient *lroauto.OperationsClient
  47. project, instance string
  48. // Metadata to be sent with each request.
  49. md metadata.MD
  50. }
  51. // NewAdminClient creates a new AdminClient for a given project and instance.
  52. func NewAdminClient(ctx context.Context, project, instance string, opts ...option.ClientOption) (*AdminClient, error) {
  53. o, err := btopt.DefaultClientOptions(adminAddr, AdminScope, clientUserAgent)
  54. if err != nil {
  55. return nil, err
  56. }
  57. // Need to add scopes for long running operations (for create table & snapshots)
  58. o = append(o, option.WithScopes(cloudresourcemanager.CloudPlatformScope))
  59. o = append(o, opts...)
  60. conn, err := gtransport.Dial(ctx, o...)
  61. if err != nil {
  62. return nil, fmt.Errorf("dialing: %v", err)
  63. }
  64. lroClient, err := lroauto.NewOperationsClient(ctx, option.WithGRPCConn(conn))
  65. if err != nil {
  66. // This error "should not happen", since we are just reusing old connection
  67. // and never actually need to dial.
  68. // If this does happen, we could leak conn. However, we cannot close conn:
  69. // If the user invoked the function with option.WithGRPCConn,
  70. // we would close a connection that's still in use.
  71. // TODO(pongad): investigate error conditions.
  72. return nil, err
  73. }
  74. return &AdminClient{
  75. conn: conn,
  76. tClient: btapb.NewBigtableTableAdminClient(conn),
  77. lroClient: lroClient,
  78. project: project,
  79. instance: instance,
  80. md: metadata.Pairs(resourcePrefixHeader, fmt.Sprintf("projects/%s/instances/%s", project, instance)),
  81. }, nil
  82. }
  83. // Close closes the AdminClient.
  84. func (ac *AdminClient) Close() error {
  85. return ac.conn.Close()
  86. }
  87. func (ac *AdminClient) instancePrefix() string {
  88. return fmt.Sprintf("projects/%s/instances/%s", ac.project, ac.instance)
  89. }
  90. // Tables returns a list of the tables in the instance.
  91. func (ac *AdminClient) Tables(ctx context.Context) ([]string, error) {
  92. ctx = mergeOutgoingMetadata(ctx, ac.md)
  93. prefix := ac.instancePrefix()
  94. req := &btapb.ListTablesRequest{
  95. Parent: prefix,
  96. }
  97. var res *btapb.ListTablesResponse
  98. err := gax.Invoke(ctx, func(ctx context.Context) error {
  99. var err error
  100. res, err = ac.tClient.ListTables(ctx, req)
  101. return err
  102. }, retryOptions...)
  103. if err != nil {
  104. return nil, err
  105. }
  106. names := make([]string, 0, len(res.Tables))
  107. for _, tbl := range res.Tables {
  108. names = append(names, strings.TrimPrefix(tbl.Name, prefix+"/tables/"))
  109. }
  110. return names, nil
  111. }
  112. // TableConf contains all of the information necessary to create a table with column families.
  113. type TableConf struct {
  114. TableID string
  115. SplitKeys []string
  116. // Families is a map from family name to GCPolicy
  117. Families map[string]GCPolicy
  118. }
  119. // CreateTable creates a new table in the instance.
  120. // This method may return before the table's creation is complete.
  121. func (ac *AdminClient) CreateTable(ctx context.Context, table string) error {
  122. return ac.CreateTableFromConf(ctx, &TableConf{TableID: table})
  123. }
  124. // CreatePresplitTable creates a new table in the instance.
  125. // The list of row keys will be used to initially split the table into multiple tablets.
  126. // Given two split keys, "s1" and "s2", three tablets will be created,
  127. // spanning the key ranges: [, s1), [s1, s2), [s2, ).
  128. // This method may return before the table's creation is complete.
  129. func (ac *AdminClient) CreatePresplitTable(ctx context.Context, table string, splitKeys []string) error {
  130. return ac.CreateTableFromConf(ctx, &TableConf{TableID: table, SplitKeys: splitKeys})
  131. }
  132. // CreateTableFromConf creates a new table in the instance from the given configuration.
  133. func (ac *AdminClient) CreateTableFromConf(ctx context.Context, conf *TableConf) error {
  134. ctx = mergeOutgoingMetadata(ctx, ac.md)
  135. var req_splits []*btapb.CreateTableRequest_Split
  136. for _, split := range conf.SplitKeys {
  137. req_splits = append(req_splits, &btapb.CreateTableRequest_Split{Key: []byte(split)})
  138. }
  139. var tbl btapb.Table
  140. if conf.Families != nil {
  141. tbl.ColumnFamilies = make(map[string]*btapb.ColumnFamily)
  142. for fam, policy := range conf.Families {
  143. tbl.ColumnFamilies[fam] = &btapb.ColumnFamily{GcRule: policy.proto()}
  144. }
  145. }
  146. prefix := ac.instancePrefix()
  147. req := &btapb.CreateTableRequest{
  148. Parent: prefix,
  149. TableId: conf.TableID,
  150. Table: &tbl,
  151. InitialSplits: req_splits,
  152. }
  153. _, err := ac.tClient.CreateTable(ctx, req)
  154. return err
  155. }
  156. // CreateColumnFamily creates a new column family in a table.
  157. func (ac *AdminClient) CreateColumnFamily(ctx context.Context, table, family string) error {
  158. // TODO(dsymonds): Permit specifying gcexpr and any other family settings.
  159. ctx = mergeOutgoingMetadata(ctx, ac.md)
  160. prefix := ac.instancePrefix()
  161. req := &btapb.ModifyColumnFamiliesRequest{
  162. Name: prefix + "/tables/" + table,
  163. Modifications: []*btapb.ModifyColumnFamiliesRequest_Modification{{
  164. Id: family,
  165. Mod: &btapb.ModifyColumnFamiliesRequest_Modification_Create{Create: &btapb.ColumnFamily{}},
  166. }},
  167. }
  168. _, err := ac.tClient.ModifyColumnFamilies(ctx, req)
  169. return err
  170. }
  171. // DeleteTable deletes a table and all of its data.
  172. func (ac *AdminClient) DeleteTable(ctx context.Context, table string) error {
  173. ctx = mergeOutgoingMetadata(ctx, ac.md)
  174. prefix := ac.instancePrefix()
  175. req := &btapb.DeleteTableRequest{
  176. Name: prefix + "/tables/" + table,
  177. }
  178. _, err := ac.tClient.DeleteTable(ctx, req)
  179. return err
  180. }
  181. // DeleteColumnFamily deletes a column family in a table and all of its data.
  182. func (ac *AdminClient) DeleteColumnFamily(ctx context.Context, table, family string) error {
  183. ctx = mergeOutgoingMetadata(ctx, ac.md)
  184. prefix := ac.instancePrefix()
  185. req := &btapb.ModifyColumnFamiliesRequest{
  186. Name: prefix + "/tables/" + table,
  187. Modifications: []*btapb.ModifyColumnFamiliesRequest_Modification{{
  188. Id: family,
  189. Mod: &btapb.ModifyColumnFamiliesRequest_Modification_Drop{Drop: true},
  190. }},
  191. }
  192. _, err := ac.tClient.ModifyColumnFamilies(ctx, req)
  193. return err
  194. }
  195. // TableInfo represents information about a table.
  196. type TableInfo struct {
  197. // DEPRECATED - This field is deprecated. Please use FamilyInfos instead.
  198. Families []string
  199. FamilyInfos []FamilyInfo
  200. }
  201. // FamilyInfo represents information about a column family.
  202. type FamilyInfo struct {
  203. Name string
  204. GCPolicy string
  205. }
  206. // TableInfo retrieves information about a table.
  207. func (ac *AdminClient) TableInfo(ctx context.Context, table string) (*TableInfo, error) {
  208. ctx = mergeOutgoingMetadata(ctx, ac.md)
  209. prefix := ac.instancePrefix()
  210. req := &btapb.GetTableRequest{
  211. Name: prefix + "/tables/" + table,
  212. }
  213. var res *btapb.Table
  214. err := gax.Invoke(ctx, func(ctx context.Context) error {
  215. var err error
  216. res, err = ac.tClient.GetTable(ctx, req)
  217. return err
  218. }, retryOptions...)
  219. if err != nil {
  220. return nil, err
  221. }
  222. ti := &TableInfo{}
  223. for name, fam := range res.ColumnFamilies {
  224. ti.Families = append(ti.Families, name)
  225. ti.FamilyInfos = append(ti.FamilyInfos, FamilyInfo{Name: name, GCPolicy: GCRuleToString(fam.GcRule)})
  226. }
  227. return ti, nil
  228. }
  229. // SetGCPolicy specifies which cells in a column family should be garbage collected.
  230. // GC executes opportunistically in the background; table reads may return data
  231. // matching the GC policy.
  232. func (ac *AdminClient) SetGCPolicy(ctx context.Context, table, family string, policy GCPolicy) error {
  233. ctx = mergeOutgoingMetadata(ctx, ac.md)
  234. prefix := ac.instancePrefix()
  235. req := &btapb.ModifyColumnFamiliesRequest{
  236. Name: prefix + "/tables/" + table,
  237. Modifications: []*btapb.ModifyColumnFamiliesRequest_Modification{{
  238. Id: family,
  239. Mod: &btapb.ModifyColumnFamiliesRequest_Modification_Update{Update: &btapb.ColumnFamily{GcRule: policy.proto()}},
  240. }},
  241. }
  242. _, err := ac.tClient.ModifyColumnFamilies(ctx, req)
  243. return err
  244. }
  245. // DropRowRange permanently deletes a row range from the specified table.
  246. func (ac *AdminClient) DropRowRange(ctx context.Context, table, rowKeyPrefix string) error {
  247. ctx = mergeOutgoingMetadata(ctx, ac.md)
  248. prefix := ac.instancePrefix()
  249. req := &btapb.DropRowRangeRequest{
  250. Name: prefix + "/tables/" + table,
  251. Target: &btapb.DropRowRangeRequest_RowKeyPrefix{RowKeyPrefix: []byte(rowKeyPrefix)},
  252. }
  253. _, err := ac.tClient.DropRowRange(ctx, req)
  254. return err
  255. }
  256. // CreateTableFromSnapshot creates a table from snapshot.
  257. // The table will be created in the same cluster as the snapshot.
  258. //
  259. // This is a private alpha release of Cloud Bigtable snapshots. This feature
  260. // is not currently available to most Cloud Bigtable customers. This feature
  261. // might be changed in backward-incompatible ways and is not recommended for
  262. // production use. It is not subject to any SLA or deprecation policy.
  263. func (ac *AdminClient) CreateTableFromSnapshot(ctx context.Context, table, cluster, snapshot string) error {
  264. ctx = mergeOutgoingMetadata(ctx, ac.md)
  265. prefix := ac.instancePrefix()
  266. snapshotPath := prefix + "/clusters/" + cluster + "/snapshots/" + snapshot
  267. req := &btapb.CreateTableFromSnapshotRequest{
  268. Parent: prefix,
  269. TableId: table,
  270. SourceSnapshot: snapshotPath,
  271. }
  272. op, err := ac.tClient.CreateTableFromSnapshot(ctx, req)
  273. if err != nil {
  274. return err
  275. }
  276. resp := btapb.Table{}
  277. return longrunning.InternalNewOperation(ac.lroClient, op).Wait(ctx, &resp)
  278. }
  279. const DefaultSnapshotDuration time.Duration = 0
  280. // Creates a new snapshot in the specified cluster from the specified source table.
  281. // Setting the ttl to `DefaultSnapshotDuration` will use the server side default for the duration.
  282. //
  283. // This is a private alpha release of Cloud Bigtable snapshots. This feature
  284. // is not currently available to most Cloud Bigtable customers. This feature
  285. // might be changed in backward-incompatible ways and is not recommended for
  286. // production use. It is not subject to any SLA or deprecation policy.
  287. func (ac *AdminClient) SnapshotTable(ctx context.Context, table, cluster, snapshot string, ttl time.Duration) error {
  288. ctx = mergeOutgoingMetadata(ctx, ac.md)
  289. prefix := ac.instancePrefix()
  290. var ttlProto *durpb.Duration
  291. if ttl > 0 {
  292. ttlProto = ptypes.DurationProto(ttl)
  293. }
  294. req := &btapb.SnapshotTableRequest{
  295. Name: prefix + "/tables/" + table,
  296. Cluster: prefix + "/clusters/" + cluster,
  297. SnapshotId: snapshot,
  298. Ttl: ttlProto,
  299. }
  300. op, err := ac.tClient.SnapshotTable(ctx, req)
  301. if err != nil {
  302. return err
  303. }
  304. resp := btapb.Snapshot{}
  305. return longrunning.InternalNewOperation(ac.lroClient, op).Wait(ctx, &resp)
  306. }
  307. // Snapshots returns a SnapshotIterator for iterating over the snapshots in a cluster.
  308. // To list snapshots across all of the clusters in the instance specify "-" as the cluster.
  309. //
  310. // This is a private alpha release of Cloud Bigtable snapshots. This feature is not
  311. // currently available to most Cloud Bigtable customers. This feature might be
  312. // changed in backward-incompatible ways and is not recommended for production use.
  313. // It is not subject to any SLA or deprecation policy.
  314. func (ac *AdminClient) Snapshots(ctx context.Context, cluster string) *SnapshotIterator {
  315. ctx = mergeOutgoingMetadata(ctx, ac.md)
  316. prefix := ac.instancePrefix()
  317. clusterPath := prefix + "/clusters/" + cluster
  318. it := &SnapshotIterator{}
  319. req := &btapb.ListSnapshotsRequest{
  320. Parent: clusterPath,
  321. }
  322. fetch := func(pageSize int, pageToken string) (string, error) {
  323. req.PageToken = pageToken
  324. if pageSize > math.MaxInt32 {
  325. req.PageSize = math.MaxInt32
  326. } else {
  327. req.PageSize = int32(pageSize)
  328. }
  329. resp, err := ac.tClient.ListSnapshots(ctx, req)
  330. if err != nil {
  331. return "", err
  332. }
  333. for _, s := range resp.Snapshots {
  334. snapshotInfo, err := newSnapshotInfo(s)
  335. if err != nil {
  336. return "", fmt.Errorf("Failed to parse snapshot proto %v", err)
  337. }
  338. it.items = append(it.items, snapshotInfo)
  339. }
  340. return resp.NextPageToken, nil
  341. }
  342. bufLen := func() int { return len(it.items) }
  343. takeBuf := func() interface{} { b := it.items; it.items = nil; return b }
  344. it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, bufLen, takeBuf)
  345. return it
  346. }
  347. func newSnapshotInfo(snapshot *btapb.Snapshot) (*SnapshotInfo, error) {
  348. nameParts := strings.Split(snapshot.Name, "/")
  349. name := nameParts[len(nameParts)-1]
  350. tablePathParts := strings.Split(snapshot.SourceTable.Name, "/")
  351. tableID := tablePathParts[len(tablePathParts)-1]
  352. createTime, err := ptypes.Timestamp(snapshot.CreateTime)
  353. if err != nil {
  354. return nil, fmt.Errorf("Invalid createTime: %v", err)
  355. }
  356. deleteTime, err := ptypes.Timestamp(snapshot.DeleteTime)
  357. if err != nil {
  358. return nil, fmt.Errorf("Invalid deleteTime: %v", err)
  359. }
  360. return &SnapshotInfo{
  361. Name: name,
  362. SourceTable: tableID,
  363. DataSize: snapshot.DataSizeBytes,
  364. CreateTime: createTime,
  365. DeleteTime: deleteTime,
  366. }, nil
  367. }
  368. // An EntryIterator iterates over log entries.
  369. //
  370. // This is a private alpha release of Cloud Bigtable snapshots. This feature
  371. // is not currently available to most Cloud Bigtable customers. This feature
  372. // might be changed in backward-incompatible ways and is not recommended for
  373. // production use. It is not subject to any SLA or deprecation policy.
  374. type SnapshotIterator struct {
  375. items []*SnapshotInfo
  376. pageInfo *iterator.PageInfo
  377. nextFunc func() error
  378. }
  379. // PageInfo supports pagination. See https://godoc.org/google.golang.org/api/iterator package for details.
  380. func (it *SnapshotIterator) PageInfo() *iterator.PageInfo {
  381. return it.pageInfo
  382. }
  383. // Next returns the next result. Its second return value is iterator.Done
  384. // (https://godoc.org/google.golang.org/api/iterator) if there are no more
  385. // results. Once Next returns Done, all subsequent calls will return Done.
  386. func (it *SnapshotIterator) Next() (*SnapshotInfo, error) {
  387. if err := it.nextFunc(); err != nil {
  388. return nil, err
  389. }
  390. item := it.items[0]
  391. it.items = it.items[1:]
  392. return item, nil
  393. }
  394. type SnapshotInfo struct {
  395. Name string
  396. SourceTable string
  397. DataSize int64
  398. CreateTime time.Time
  399. DeleteTime time.Time
  400. }
  401. // Get snapshot metadata.
  402. //
  403. // This is a private alpha release of Cloud Bigtable snapshots. This feature
  404. // is not currently available to most Cloud Bigtable customers. This feature
  405. // might be changed in backward-incompatible ways and is not recommended for
  406. // production use. It is not subject to any SLA or deprecation policy.
  407. func (ac *AdminClient) SnapshotInfo(ctx context.Context, cluster, snapshot string) (*SnapshotInfo, error) {
  408. ctx = mergeOutgoingMetadata(ctx, ac.md)
  409. prefix := ac.instancePrefix()
  410. clusterPath := prefix + "/clusters/" + cluster
  411. snapshotPath := clusterPath + "/snapshots/" + snapshot
  412. req := &btapb.GetSnapshotRequest{
  413. Name: snapshotPath,
  414. }
  415. resp, err := ac.tClient.GetSnapshot(ctx, req)
  416. if err != nil {
  417. return nil, err
  418. }
  419. return newSnapshotInfo(resp)
  420. }
  421. // Delete a snapshot in a cluster.
  422. //
  423. // This is a private alpha release of Cloud Bigtable snapshots. This feature
  424. // is not currently available to most Cloud Bigtable customers. This feature
  425. // might be changed in backward-incompatible ways and is not recommended for
  426. // production use. It is not subject to any SLA or deprecation policy.
  427. func (ac *AdminClient) DeleteSnapshot(ctx context.Context, cluster, snapshot string) error {
  428. ctx = mergeOutgoingMetadata(ctx, ac.md)
  429. prefix := ac.instancePrefix()
  430. clusterPath := prefix + "/clusters/" + cluster
  431. snapshotPath := clusterPath + "/snapshots/" + snapshot
  432. req := &btapb.DeleteSnapshotRequest{
  433. Name: snapshotPath,
  434. }
  435. _, err := ac.tClient.DeleteSnapshot(ctx, req)
  436. return err
  437. }
  438. // getConsistencyToken gets the consistency token for a table.
  439. func (ac *AdminClient) getConsistencyToken(ctx context.Context, tableName string) (string, error) {
  440. req := &btapb.GenerateConsistencyTokenRequest{
  441. Name: tableName,
  442. }
  443. resp, err := ac.tClient.GenerateConsistencyToken(ctx, req)
  444. if err != nil {
  445. return "", err
  446. }
  447. return resp.GetConsistencyToken(), nil
  448. }
  449. // isConsistent checks if a token is consistent for a table.
  450. func (ac *AdminClient) isConsistent(ctx context.Context, tableName, token string) (bool, error) {
  451. req := &btapb.CheckConsistencyRequest{
  452. Name: tableName,
  453. ConsistencyToken: token,
  454. }
  455. var resp *btapb.CheckConsistencyResponse
  456. // Retry calls on retryable errors to avoid losing the token gathered before.
  457. err := gax.Invoke(ctx, func(ctx context.Context) error {
  458. var err error
  459. resp, err = ac.tClient.CheckConsistency(ctx, req)
  460. return err
  461. }, retryOptions...)
  462. if err != nil {
  463. return false, err
  464. }
  465. return resp.GetConsistent(), nil
  466. }
  467. // WaitForReplication waits until all the writes committed before the call started have been propagated to all the clusters in the instance via replication.
  468. //
  469. // This is a private alpha release of Cloud Bigtable replication. This feature
  470. // is not currently available to most Cloud Bigtable customers. This feature
  471. // might be changed in backward-incompatible ways and is not recommended for
  472. // production use. It is not subject to any SLA or deprecation policy.
  473. func (ac *AdminClient) WaitForReplication(ctx context.Context, table string) error {
  474. // Get the token.
  475. prefix := ac.instancePrefix()
  476. tableName := prefix + "/tables/" + table
  477. token, err := ac.getConsistencyToken(ctx, tableName)
  478. if err != nil {
  479. return err
  480. }
  481. // Periodically check if the token is consistent.
  482. timer := time.NewTicker(time.Second * 10)
  483. defer timer.Stop()
  484. for {
  485. consistent, err := ac.isConsistent(ctx, tableName, token)
  486. if err != nil {
  487. return err
  488. }
  489. if consistent {
  490. return nil
  491. }
  492. // Sleep for a bit or until the ctx is cancelled.
  493. select {
  494. case <-ctx.Done():
  495. return ctx.Err()
  496. case <-timer.C:
  497. }
  498. }
  499. }
  500. const instanceAdminAddr = "bigtableadmin.googleapis.com:443"
  501. // InstanceAdminClient is a client type for performing admin operations on instances.
  502. // These operations can be substantially more dangerous than those provided by AdminClient.
  503. type InstanceAdminClient struct {
  504. conn *grpc.ClientConn
  505. iClient btapb.BigtableInstanceAdminClient
  506. lroClient *lroauto.OperationsClient
  507. project string
  508. // Metadata to be sent with each request.
  509. md metadata.MD
  510. }
  511. // NewInstanceAdminClient creates a new InstanceAdminClient for a given project.
  512. func NewInstanceAdminClient(ctx context.Context, project string, opts ...option.ClientOption) (*InstanceAdminClient, error) {
  513. o, err := btopt.DefaultClientOptions(instanceAdminAddr, InstanceAdminScope, clientUserAgent)
  514. if err != nil {
  515. return nil, err
  516. }
  517. o = append(o, opts...)
  518. conn, err := gtransport.Dial(ctx, o...)
  519. if err != nil {
  520. return nil, fmt.Errorf("dialing: %v", err)
  521. }
  522. lroClient, err := lroauto.NewOperationsClient(ctx, option.WithGRPCConn(conn))
  523. if err != nil {
  524. // This error "should not happen", since we are just reusing old connection
  525. // and never actually need to dial.
  526. // If this does happen, we could leak conn. However, we cannot close conn:
  527. // If the user invoked the function with option.WithGRPCConn,
  528. // we would close a connection that's still in use.
  529. // TODO(pongad): investigate error conditions.
  530. return nil, err
  531. }
  532. return &InstanceAdminClient{
  533. conn: conn,
  534. iClient: btapb.NewBigtableInstanceAdminClient(conn),
  535. lroClient: lroClient,
  536. project: project,
  537. md: metadata.Pairs(resourcePrefixHeader, "projects/"+project),
  538. }, nil
  539. }
  540. // Close closes the InstanceAdminClient.
  541. func (iac *InstanceAdminClient) Close() error {
  542. return iac.conn.Close()
  543. }
  544. // StorageType is the type of storage used for all tables in an instance
  545. type StorageType int
  546. const (
  547. SSD StorageType = iota
  548. HDD
  549. )
  550. func (st StorageType) proto() btapb.StorageType {
  551. if st == HDD {
  552. return btapb.StorageType_HDD
  553. }
  554. return btapb.StorageType_SSD
  555. }
  556. // InstanceType is the type of the instance
  557. type InstanceType int32
  558. const (
  559. PRODUCTION InstanceType = InstanceType(btapb.Instance_PRODUCTION)
  560. DEVELOPMENT = InstanceType(btapb.Instance_DEVELOPMENT)
  561. )
  562. // InstanceInfo represents information about an instance
  563. type InstanceInfo struct {
  564. Name string // name of the instance
  565. DisplayName string // display name for UIs
  566. }
  567. // InstanceConf contains the information necessary to create an Instance
  568. type InstanceConf struct {
  569. InstanceId, DisplayName, ClusterId, Zone string
  570. // NumNodes must not be specified for DEVELOPMENT instance types
  571. NumNodes int32
  572. StorageType StorageType
  573. InstanceType InstanceType
  574. }
  575. // InstanceWithClustersConfig contains the information necessary to create an Instance
  576. type InstanceWithClustersConfig struct {
  577. InstanceID, DisplayName string
  578. Clusters []ClusterConfig
  579. InstanceType InstanceType
  580. }
  581. var instanceNameRegexp = regexp.MustCompile(`^projects/([^/]+)/instances/([a-z][-a-z0-9]*)$`)
  582. // CreateInstance creates a new instance in the project.
  583. // This method will return when the instance has been created or when an error occurs.
  584. func (iac *InstanceAdminClient) CreateInstance(ctx context.Context, conf *InstanceConf) error {
  585. newConfig := InstanceWithClustersConfig{
  586. InstanceID: conf.InstanceId,
  587. DisplayName: conf.DisplayName,
  588. InstanceType: conf.InstanceType,
  589. Clusters: []ClusterConfig{
  590. {
  591. InstanceID: conf.InstanceId,
  592. ClusterID: conf.ClusterId,
  593. Zone: conf.Zone,
  594. NumNodes: conf.NumNodes,
  595. StorageType: conf.StorageType,
  596. },
  597. },
  598. }
  599. return iac.CreateInstanceWithClusters(ctx, &newConfig)
  600. }
  601. // CreateInstance creates a new instance with configured clusters in the project.
  602. // This method will return when the instance has been created or when an error occurs.
  603. //
  604. // Instances with multiple clusters are part of a private alpha release of Cloud Bigtable replication.
  605. // This feature is not currently available to most Cloud Bigtable customers. This feature
  606. // might be changed in backward-incompatible ways and is not recommended for
  607. // production use. It is not subject to any SLA or deprecation policy.
  608. func (iac *InstanceAdminClient) CreateInstanceWithClusters(ctx context.Context, conf *InstanceWithClustersConfig) error {
  609. ctx = mergeOutgoingMetadata(ctx, iac.md)
  610. clusters := make(map[string]*btapb.Cluster)
  611. for _, cluster := range conf.Clusters {
  612. clusters[cluster.ClusterID] = cluster.proto(iac.project)
  613. }
  614. req := &btapb.CreateInstanceRequest{
  615. Parent: "projects/" + iac.project,
  616. InstanceId: conf.InstanceID,
  617. Instance: &btapb.Instance{DisplayName: conf.DisplayName, Type: btapb.Instance_Type(conf.InstanceType)},
  618. Clusters: clusters,
  619. }
  620. lro, err := iac.iClient.CreateInstance(ctx, req)
  621. if err != nil {
  622. return err
  623. }
  624. resp := btapb.Instance{}
  625. return longrunning.InternalNewOperation(iac.lroClient, lro).Wait(ctx, &resp)
  626. }
  627. // DeleteInstance deletes an instance from the project.
  628. func (iac *InstanceAdminClient) DeleteInstance(ctx context.Context, instanceID string) error {
  629. ctx = mergeOutgoingMetadata(ctx, iac.md)
  630. req := &btapb.DeleteInstanceRequest{Name: "projects/" + iac.project + "/instances/" + instanceID}
  631. _, err := iac.iClient.DeleteInstance(ctx, req)
  632. return err
  633. }
  634. // Instances returns a list of instances in the project.
  635. func (iac *InstanceAdminClient) Instances(ctx context.Context) ([]*InstanceInfo, error) {
  636. ctx = mergeOutgoingMetadata(ctx, iac.md)
  637. req := &btapb.ListInstancesRequest{
  638. Parent: "projects/" + iac.project,
  639. }
  640. res, err := iac.iClient.ListInstances(ctx, req)
  641. if err != nil {
  642. return nil, err
  643. }
  644. if len(res.FailedLocations) > 0 {
  645. // We don't have a good way to return a partial result in the face of some zones being unavailable.
  646. // Fail the entire request.
  647. return nil, status.Errorf(codes.Unavailable, "Failed locations: %v", res.FailedLocations)
  648. }
  649. var is []*InstanceInfo
  650. for _, i := range res.Instances {
  651. m := instanceNameRegexp.FindStringSubmatch(i.Name)
  652. if m == nil {
  653. return nil, fmt.Errorf("malformed instance name %q", i.Name)
  654. }
  655. is = append(is, &InstanceInfo{
  656. Name: m[2],
  657. DisplayName: i.DisplayName,
  658. })
  659. }
  660. return is, nil
  661. }
  662. // InstanceInfo returns information about an instance.
  663. func (iac *InstanceAdminClient) InstanceInfo(ctx context.Context, instanceID string) (*InstanceInfo, error) {
  664. ctx = mergeOutgoingMetadata(ctx, iac.md)
  665. req := &btapb.GetInstanceRequest{
  666. Name: "projects/" + iac.project + "/instances/" + instanceID,
  667. }
  668. res, err := iac.iClient.GetInstance(ctx, req)
  669. if err != nil {
  670. return nil, err
  671. }
  672. m := instanceNameRegexp.FindStringSubmatch(res.Name)
  673. if m == nil {
  674. return nil, fmt.Errorf("malformed instance name %q", res.Name)
  675. }
  676. return &InstanceInfo{
  677. Name: m[2],
  678. DisplayName: res.DisplayName,
  679. }, nil
  680. }
  681. // ClusterConfig contains the information necessary to create a cluster
  682. type ClusterConfig struct {
  683. InstanceID, ClusterID, Zone string
  684. NumNodes int32
  685. StorageType StorageType
  686. }
  687. func (cc *ClusterConfig) proto(project string) *btapb.Cluster {
  688. return &btapb.Cluster{
  689. ServeNodes: cc.NumNodes,
  690. DefaultStorageType: cc.StorageType.proto(),
  691. Location: "projects/" + project + "/locations/" + cc.Zone,
  692. }
  693. }
  694. // ClusterInfo represents information about a cluster.
  695. type ClusterInfo struct {
  696. Name string // name of the cluster
  697. Zone string // GCP zone of the cluster (e.g. "us-central1-a")
  698. ServeNodes int // number of allocated serve nodes
  699. State string // state of the cluster
  700. }
  701. // CreateCluster creates a new cluster in an instance.
  702. // This method will return when the cluster has been created or when an error occurs.
  703. //
  704. // This is a private alpha release of Cloud Bigtable replication. This feature
  705. // is not currently available to most Cloud Bigtable customers. This feature
  706. // might be changed in backward-incompatible ways and is not recommended for
  707. // production use. It is not subject to any SLA or deprecation policy.
  708. func (iac *InstanceAdminClient) CreateCluster(ctx context.Context, conf *ClusterConfig) error {
  709. ctx = mergeOutgoingMetadata(ctx, iac.md)
  710. req := &btapb.CreateClusterRequest{
  711. Parent: "projects/" + iac.project + "/instances/" + conf.InstanceID,
  712. ClusterId: conf.ClusterID,
  713. Cluster: conf.proto(iac.project),
  714. }
  715. lro, err := iac.iClient.CreateCluster(ctx, req)
  716. if err != nil {
  717. return err
  718. }
  719. resp := btapb.Cluster{}
  720. return longrunning.InternalNewOperation(iac.lroClient, lro).Wait(ctx, &resp)
  721. }
  722. // DeleteCluster deletes a cluster from an instance.
  723. //
  724. // This is a private alpha release of Cloud Bigtable replication. This feature
  725. // is not currently available to most Cloud Bigtable customers. This feature
  726. // might be changed in backward-incompatible ways and is not recommended for
  727. // production use. It is not subject to any SLA or deprecation policy.
  728. func (iac *InstanceAdminClient) DeleteCluster(ctx context.Context, instanceID, clusterID string) error {
  729. ctx = mergeOutgoingMetadata(ctx, iac.md)
  730. req := &btapb.DeleteClusterRequest{Name: "projects/" + iac.project + "/instances/" + instanceID + "/clusters/" + clusterID}
  731. _, err := iac.iClient.DeleteCluster(ctx, req)
  732. return err
  733. }
  734. // UpdateCluster updates attributes of a cluster
  735. func (iac *InstanceAdminClient) UpdateCluster(ctx context.Context, instanceID, clusterID string, serveNodes int32) error {
  736. ctx = mergeOutgoingMetadata(ctx, iac.md)
  737. cluster := &btapb.Cluster{
  738. Name: "projects/" + iac.project + "/instances/" + instanceID + "/clusters/" + clusterID,
  739. ServeNodes: serveNodes}
  740. lro, err := iac.iClient.UpdateCluster(ctx, cluster)
  741. if err != nil {
  742. return err
  743. }
  744. return longrunning.InternalNewOperation(iac.lroClient, lro).Wait(ctx, nil)
  745. }
  746. // Clusters lists the clusters in an instance.
  747. func (iac *InstanceAdminClient) Clusters(ctx context.Context, instanceID string) ([]*ClusterInfo, error) {
  748. ctx = mergeOutgoingMetadata(ctx, iac.md)
  749. req := &btapb.ListClustersRequest{Parent: "projects/" + iac.project + "/instances/" + instanceID}
  750. res, err := iac.iClient.ListClusters(ctx, req)
  751. if err != nil {
  752. return nil, err
  753. }
  754. // TODO(garyelliott): Deal with failed_locations.
  755. var cis []*ClusterInfo
  756. for _, c := range res.Clusters {
  757. nameParts := strings.Split(c.Name, "/")
  758. locParts := strings.Split(c.Location, "/")
  759. cis = append(cis, &ClusterInfo{
  760. Name: nameParts[len(nameParts)-1],
  761. Zone: locParts[len(locParts)-1],
  762. ServeNodes: int(c.ServeNodes),
  763. State: c.State.String(),
  764. })
  765. }
  766. return cis, nil
  767. }
  768. // GetCluster fetches a cluster in an instance
  769. func (iac *InstanceAdminClient) GetCluster(ctx context.Context, instanceID, clusterID string) (*ClusterInfo, error) {
  770. ctx = mergeOutgoingMetadata(ctx, iac.md)
  771. req := &btapb.GetClusterRequest{Name: "projects/" + iac.project + "/instances/" + instanceID + "/clusters/" + clusterID}
  772. c, err := iac.iClient.GetCluster(ctx, req)
  773. if err != nil {
  774. return nil, err
  775. }
  776. nameParts := strings.Split(c.Name, "/")
  777. locParts := strings.Split(c.Location, "/")
  778. cis := &ClusterInfo{
  779. Name: nameParts[len(nameParts)-1],
  780. Zone: locParts[len(locParts)-1],
  781. ServeNodes: int(c.ServeNodes),
  782. State: c.State.String(),
  783. }
  784. return cis, nil
  785. }
  786. func (iac *InstanceAdminClient) InstanceIAM(instanceID string) *iam.Handle {
  787. return iam.InternalNewHandleGRPCClient(iac.iClient, "projects/"+iac.project+"/instances/"+instanceID)
  788. }
  789. // Routing policies.
  790. const (
  791. MultiClusterRouting = "multi_cluster_routing_use_any"
  792. SingleClusterRouting = "single_cluster_routing"
  793. )
  794. // ProfileConf contains the information necessary to create an profile
  795. type ProfileConf struct {
  796. Name string
  797. ProfileID string
  798. InstanceID string
  799. Etag string
  800. Description string
  801. RoutingPolicy string
  802. ClusterID string
  803. AllowTransactionalWrites bool
  804. }
  805. type ProfileIterator struct {
  806. items []*btapb.AppProfile
  807. pageInfo *iterator.PageInfo
  808. nextFunc func() error
  809. }
  810. //set this to patch app profile. If unset, no fields will be replaced.
  811. type ProfileAttrsToUpdate struct {
  812. // If set, updates the description.
  813. Description optional.String
  814. //If set, updates the routing policy.
  815. RoutingPolicy optional.String
  816. //If RoutingPolicy is updated to SingleClusterRouting, set these fields as well.
  817. ClusterID string
  818. AllowTransactionalWrites bool
  819. }
  820. func (p *ProfileAttrsToUpdate) GetFieldMaskPath() []string {
  821. path := make([]string, 0)
  822. if p.Description != nil {
  823. path = append(path, "description")
  824. }
  825. if p.RoutingPolicy != nil {
  826. path = append(path, optional.ToString(p.RoutingPolicy))
  827. }
  828. return path
  829. }
  830. // PageInfo supports pagination. See https://godoc.org/google.golang.org/api/iterator package for details.
  831. func (it *ProfileIterator) PageInfo() *iterator.PageInfo {
  832. return it.pageInfo
  833. }
  834. // Next returns the next result. Its second return value is iterator.Done
  835. // (https://godoc.org/google.golang.org/api/iterator) if there are no more
  836. // results. Once Next returns Done, all subsequent calls will return Done.
  837. func (it *ProfileIterator) Next() (*btapb.AppProfile, error) {
  838. if err := it.nextFunc(); err != nil {
  839. return nil, err
  840. }
  841. item := it.items[0]
  842. it.items = it.items[1:]
  843. return item, nil
  844. }
  845. // CreateAppProfile creates an app profile within an instance.
  846. func (iac *InstanceAdminClient) CreateAppProfile(ctx context.Context, profile ProfileConf) (*btapb.AppProfile, error) {
  847. ctx = mergeOutgoingMetadata(ctx, iac.md)
  848. parent := "projects/" + iac.project + "/instances/" + profile.InstanceID
  849. appProfile := &btapb.AppProfile{
  850. Etag: profile.Etag,
  851. Description: profile.Description,
  852. }
  853. if profile.RoutingPolicy == "" {
  854. return nil, errors.New("invalid routing policy")
  855. }
  856. switch profile.RoutingPolicy {
  857. case MultiClusterRouting:
  858. appProfile.RoutingPolicy = &btapb.AppProfile_MultiClusterRoutingUseAny_{
  859. MultiClusterRoutingUseAny: &btapb.AppProfile_MultiClusterRoutingUseAny{},
  860. }
  861. case SingleClusterRouting:
  862. appProfile.RoutingPolicy = &btapb.AppProfile_SingleClusterRouting_{
  863. SingleClusterRouting: &btapb.AppProfile_SingleClusterRouting{
  864. ClusterId: profile.ClusterID,
  865. AllowTransactionalWrites: profile.AllowTransactionalWrites,
  866. },
  867. }
  868. default:
  869. return nil, errors.New("invalid routing policy")
  870. }
  871. return iac.iClient.CreateAppProfile(ctx, &btapb.CreateAppProfileRequest{
  872. Parent: parent,
  873. AppProfile: appProfile,
  874. AppProfileId: profile.ProfileID,
  875. IgnoreWarnings: true,
  876. })
  877. }
  878. // GetAppProfile gets information about an app profile.
  879. func (iac *InstanceAdminClient) GetAppProfile(ctx context.Context, instanceID, name string) (*btapb.AppProfile, error) {
  880. ctx = mergeOutgoingMetadata(ctx, iac.md)
  881. profileRequest := &btapb.GetAppProfileRequest{
  882. Name: "projects/" + iac.project + "/instances/" + instanceID + "/appProfiles/" + name,
  883. }
  884. return iac.iClient.GetAppProfile(ctx, profileRequest)
  885. }
  886. // ListAppProfiles lists information about app profiles in an instance.
  887. func (iac *InstanceAdminClient) ListAppProfiles(ctx context.Context, instanceID string) *ProfileIterator {
  888. ctx = mergeOutgoingMetadata(ctx, iac.md)
  889. listRequest := &btapb.ListAppProfilesRequest{
  890. Parent: "projects/" + iac.project + "/instances/" + instanceID,
  891. }
  892. pit := &ProfileIterator{}
  893. fetch := func(pageSize int, pageToken string) (string, error) {
  894. listRequest.PageToken = pageToken
  895. profileRes, err := iac.iClient.ListAppProfiles(ctx, listRequest)
  896. if err != nil {
  897. return "", err
  898. }
  899. for _, a := range profileRes.AppProfiles {
  900. pit.items = append(pit.items, a)
  901. }
  902. return profileRes.NextPageToken, nil
  903. }
  904. bufLen := func() int { return len(pit.items) }
  905. takeBuf := func() interface{} { b := pit.items; pit.items = nil; return b }
  906. pit.pageInfo, pit.nextFunc = iterator.NewPageInfo(fetch, bufLen, takeBuf)
  907. return pit
  908. }
  909. // UpdateAppProfile updates an app profile within an instance.
  910. // updateAttrs should be set. If unset, all fields will be replaced.
  911. func (iac *InstanceAdminClient) UpdateAppProfile(ctx context.Context, instanceID, profileID string, updateAttrs ProfileAttrsToUpdate) error {
  912. ctx = mergeOutgoingMetadata(ctx, iac.md)
  913. profile := &btapb.AppProfile{
  914. Name: "projects/" + iac.project + "/instances/" + instanceID + "/appProfiles/" + profileID,
  915. }
  916. if updateAttrs.Description != nil {
  917. profile.Description = optional.ToString(updateAttrs.Description)
  918. }
  919. if updateAttrs.RoutingPolicy != nil {
  920. switch optional.ToString(updateAttrs.RoutingPolicy) {
  921. case MultiClusterRouting:
  922. profile.RoutingPolicy = &btapb.AppProfile_MultiClusterRoutingUseAny_{
  923. MultiClusterRoutingUseAny: &btapb.AppProfile_MultiClusterRoutingUseAny{},
  924. }
  925. case SingleClusterRouting:
  926. profile.RoutingPolicy = &btapb.AppProfile_SingleClusterRouting_{
  927. SingleClusterRouting: &btapb.AppProfile_SingleClusterRouting{
  928. ClusterId: updateAttrs.ClusterID,
  929. AllowTransactionalWrites: updateAttrs.AllowTransactionalWrites,
  930. },
  931. }
  932. default:
  933. return errors.New("invalid routing policy")
  934. }
  935. }
  936. patchRequest := &btapb.UpdateAppProfileRequest{
  937. AppProfile: profile,
  938. UpdateMask: &field_mask.FieldMask{
  939. Paths: updateAttrs.GetFieldMaskPath(),
  940. },
  941. IgnoreWarnings: true,
  942. }
  943. updateRequest, err := iac.iClient.UpdateAppProfile(ctx, patchRequest)
  944. if err != nil {
  945. return err
  946. }
  947. return longrunning.InternalNewOperation(iac.lroClient, updateRequest).Wait(ctx, nil)
  948. }
  949. // DeleteAppProfile deletes an app profile from an instance.
  950. func (iac *InstanceAdminClient) DeleteAppProfile(ctx context.Context, instanceID, name string) error {
  951. ctx = mergeOutgoingMetadata(ctx, iac.md)
  952. deleteProfileRequest := &btapb.DeleteAppProfileRequest{
  953. Name: "projects/" + iac.project + "/instances/" + instanceID + "/appProfiles/" + name,
  954. IgnoreWarnings: true,
  955. }
  956. _, err := iac.iClient.DeleteAppProfile(ctx, deleteProfileRequest)
  957. return err
  958. }