-
Notifications
You must be signed in to change notification settings - Fork 2.3k
discoveryengine: add pre-delete hook to detach stores on destroy #17273
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
btkelly
wants to merge
1
commit into
GoogleCloudPlatform:main
Choose a base branch
from
btkelly:fix-data-connector-deletion
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+239
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
134 changes: 134 additions & 0 deletions
134
mmv1/templates/terraform/pre_delete/discoveryengine_data_connector.go.tmpl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| if d.Get("detach_stores_on_destroy").(bool) { | ||
| log.Printf("[DEBUG] detach_stores_on_destroy is true, checking for linked search engines") | ||
|
|
||
| // 1. Get stores from entities | ||
| entitiesObj := d.Get("entities") | ||
| entities, ok := entitiesObj.([]interface{}) | ||
| if !ok { | ||
| return fmt.Errorf("error converting entities to []interface{}") | ||
| } | ||
|
|
||
| var storeIds []string | ||
| for _, entityObj := range entities { | ||
| entity, ok := entityObj.(map[string]interface{}) | ||
| if !ok { | ||
| continue | ||
| } | ||
| storeNameObj, ok := entity["data_store"] | ||
| if !ok { | ||
| continue | ||
| } | ||
| storeName, ok := storeNameObj.(string) | ||
| if !ok || storeName == "" { | ||
| continue | ||
| } | ||
| // Extract store ID from full name: projects/*/locations/*/collections/*/dataStores/* | ||
| parts := strings.Split(storeName, "/") | ||
| if len(parts) > 0 { | ||
| storeIds = append(storeIds, parts[len(parts)-1]) | ||
| } | ||
| } | ||
|
|
||
| if len(storeIds) == 0 { | ||
| log.Printf("[DEBUG] No stores found in DataConnector to detach") | ||
| return nil | ||
| } | ||
|
|
||
| log.Printf("[DEBUG] Stores to detach: %v", storeIds) | ||
|
|
||
| // 2. List engines in the collection | ||
| project, err := tpgresource.GetProject(d, config) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| location := d.Get("location").(string) | ||
| collectionId := d.Get("collection_id").(string) | ||
|
|
||
| baseUrl, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}DiscoveryEngineBasePath{{"}}"}}") | ||
| if err != nil { | ||
| return err | ||
| } | ||
| enginesUrl := baseUrl + fmt.Sprintf("projects/%s/locations/%s/collections/%s/engines", project, location, collectionId) | ||
|
|
||
| resp, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ | ||
| Config: config, | ||
| Method: "GET", | ||
| Project: project, | ||
| RawURL: enginesUrl, | ||
| UserAgent: userAgent, | ||
| }) | ||
| if err != nil { | ||
| return fmt.Errorf("error listing engines: %s", err) | ||
| } | ||
|
|
||
| enginesObj, ok := resp["engines"] | ||
| if !ok { | ||
| log.Printf("[DEBUG] No engines found in collection") | ||
| return nil | ||
| } | ||
| engines, ok := enginesObj.([]interface{}) | ||
| if !ok { | ||
| return fmt.Errorf("error converting engines to []interface{}") | ||
| } | ||
|
|
||
| for _, engineObj := range engines { | ||
| engine, ok := engineObj.(map[string]interface{}) | ||
| if !ok { | ||
| continue | ||
| } | ||
| engineName := engine["name"].(string) | ||
| dataStoreIdsObj, ok := engine["dataStoreIds"] | ||
| if !ok { | ||
| continue | ||
| } | ||
| dataStoreIds, ok := dataStoreIdsObj.([]interface{}) | ||
| if !ok { | ||
| continue | ||
| } | ||
|
|
||
| var newStoreIds []string | ||
| modified := false | ||
| for _, idObj := range dataStoreIds { | ||
| id, ok := idObj.(string) | ||
| if !ok { | ||
| continue | ||
| } | ||
| matched := false | ||
| for _, targetId := range storeIds { | ||
| if id == targetId { | ||
| matched = true | ||
| modified = true | ||
| break | ||
| } | ||
| } | ||
| if !matched { | ||
| newStoreIds = append(newStoreIds, id) | ||
| } | ||
| } | ||
|
|
||
| if modified { | ||
| log.Printf("[DEBUG] Detaching stores from engine %s", engineName) | ||
| // Call PATCH on engine to update dataStoreIds | ||
| engineUrl := baseUrl + engineName | ||
| updateMask := "dataStoreIds" | ||
|
|
||
| // Construct request body | ||
| body := map[string]interface{}{ | ||
| "dataStoreIds": newStoreIds, | ||
| } | ||
|
|
||
| _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ | ||
| Config: config, | ||
| Method: "PATCH", | ||
| Project: project, | ||
| RawURL: engineUrl + "?updateMask=" + updateMask, | ||
| UserAgent: userAgent, | ||
| Body: body, | ||
| }) | ||
| if err != nil { | ||
| return fmt.Errorf("error updating engine %s: %s", engineName, err) | ||
| } | ||
| log.Printf("[DEBUG] Successfully detached stores from engine %s", engineName) | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -256,3 +256,97 @@ func TestAccDiscoveryEngineDataConnector_DataConnectorEntitiesParamsDiffSuppress | |
| } | ||
| } | ||
| } | ||
|
|
||
| func TestAccDiscoveryEngineDataConnector_detachStoresOnDestroy(t *testing.T) { | ||
| // Skips this test as it requires complex IdP setup. | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. could you elaborate on the "complex IdP setup"? Generally we still like to have tests for things with complex setups (in fact it can be a useful reference later if we need to debug the resource.) |
||
| t.Skip() | ||
|
|
||
| t.Parallel() | ||
|
|
||
| context := map[string]interface{}{ | ||
| "random_suffix": acctest.RandString(t, 10), | ||
| } | ||
|
|
||
| acctest.VcrTest(t, resource.TestCase{ | ||
| PreCheck: func() { acctest.AccTestPreCheck(t) }, | ||
| ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), | ||
| ExternalProviders: map[string]resource.ExternalProvider{ | ||
| "time": {}, | ||
| }, | ||
| Steps: []resource.TestStep{ | ||
| { | ||
| Config: testAccDiscoveryEngineDataConnector_detachStoresOnDestroy(context), | ||
| }, | ||
| { | ||
| ResourceName: "google_discovery_engine_data_connector.servicenow-basic", | ||
| ImportState: true, | ||
| ImportStateVerify: true, | ||
| ImportStateVerifyIgnore: []string{"collection_display_name", "collection_id", "location", "params", "update_time", "action_config.0.action_params", "action_config.0.create_bap_connection"}, | ||
| }, | ||
| }, | ||
| }) | ||
| } | ||
|
|
||
| func testAccDiscoveryEngineDataConnector_detachStoresOnDestroy(context map[string]interface{}) string { | ||
| return acctest.Nprintf(` | ||
| resource "google_discovery_engine_data_connector" "servicenow-basic" { | ||
| location = "global" | ||
| collection_id = "tf-test-collection-id%{random_suffix}" | ||
| collection_display_name = "tf-test-dataconnector-servicenow" | ||
| data_source = "servicenow" | ||
| data_source_version = 3 | ||
| params = { | ||
| auth_type = "OAUTH_PASSWORD_GRANT" | ||
| instance_uri = "https://gcpconnector1.service-now.com/" | ||
| client_id = "SECRET_MANAGER_RESOURCE_NAME" | ||
| client_secret = "SECRET_MANAGER_RESOURCE_NAME" | ||
| static_ip_enabled = "false" | ||
| user_account = "connectorsuserqa@google.com" | ||
| password = "SECRET_MANAGER_RESOURCE_NAME" | ||
| } | ||
| refresh_interval = "86400s" | ||
| entities { | ||
| entity_name = "catalog" | ||
|
|
||
| params = jsonencode({ | ||
| "inclusion_filters" : { | ||
| "knowledgeBaseSysId" : [ | ||
| "123" | ||
| ] | ||
| } | ||
| }) | ||
| } | ||
| entities { | ||
| entity_name = "incident" | ||
| params = jsonencode({ | ||
| "inclusion_filters" : { | ||
| "knowledgeBaseSysId" : [ | ||
| "123" | ||
| ] | ||
| } | ||
| }) | ||
| } | ||
| entities { | ||
| entity_name = "knowledge_base" | ||
| params = jsonencode({ | ||
| "inclusion_filters" : { | ||
| "knowledgeBaseSysId" : [ | ||
| "123" | ||
| ] | ||
| } | ||
| }) | ||
| } | ||
| static_ip_enabled = false | ||
| destination_configs { | ||
| key = "url" | ||
| destinations { | ||
| host = "https://gcpconnector1.service-now.com/" | ||
| port = 123 | ||
| } | ||
| } | ||
| connector_modes = ["DATA_INGESTION"] | ||
| sync_mode = "PERIODIC" | ||
| detach_stores_on_destroy = true | ||
| } | ||
| `, context) | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This seems like it could be a good candidate for a deletion_policy field that has a FORCE option (which would trigger detaching stores). What would you think about that? Some more information on deletion policy fields at https://googlecloudplatform.github.io/magic-modules/best-practices/deletion-behaviors/ (though it's a bit sparse... basically it's a virtual field like you have, but it takes an enum rather than a bool.)