Skip to content

Commit

Permalink
Change error strings, add details for grant parsing (#141)
Browse files Browse the repository at this point in the history
I added everywhere [DEBUG] as that is how it should be when logging for
TF provider.

Also grant parsing gets more detailed logging to catch errors.
  • Loading branch information
petoju authored Apr 25, 2024
1 parent c7dfa94 commit cf05886
Show file tree
Hide file tree
Showing 10 changed files with 50 additions and 49 deletions.
8 changes: 4 additions & 4 deletions mysql/resource_database.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func CreateDatabase(ctx context.Context, d *schema.ResourceData, meta interface{
}

stmtSQL := databaseConfigSQL("CREATE", d)
log.Println("Executing statement:", stmtSQL)
log.Println("[DEBUG] Executing statement:", stmtSQL)

_, err = db.ExecContext(ctx, stmtSQL)
if err != nil {
Expand All @@ -74,7 +74,7 @@ func UpdateDatabase(ctx context.Context, d *schema.ResourceData, meta interface{
}

stmtSQL := databaseConfigSQL("ALTER", d)
log.Println("Executing statement:", stmtSQL)
log.Println("[DEBUG] Executing statement:", stmtSQL)

_, err = db.ExecContext(ctx, stmtSQL)
if err != nil {
Expand All @@ -98,7 +98,7 @@ func ReadDatabase(ctx context.Context, d *schema.ResourceData, meta interface{})
name := d.Id()
stmtSQL := "SHOW CREATE DATABASE " + quoteIdentifier(name)

log.Println("Executing query:", stmtSQL)
log.Println("[DEBUG] Executing query:", stmtSQL)
var createSQL, _database string
err = db.QueryRowContext(ctx, stmtSQL).Scan(&_database, &createSQL)
if err != nil {
Expand Down Expand Up @@ -160,7 +160,7 @@ func DeleteDatabase(ctx context.Context, d *schema.ResourceData, meta interface{

name := d.Id()
stmtSQL := "DROP DATABASE " + quoteIdentifier(name)
log.Println("Executing statement:", stmtSQL)
log.Println("[DEBUG] Executing statement:", stmtSQL)

_, err = db.ExecContext(ctx, stmtSQL)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions mysql/resource_default_roles.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func alterUserDefaultRoles(ctx context.Context, db *sql.DB, user, host string, r
stmtSQL += "NONE"
}

log.Println("Executing statement:", stmtSQL)
log.Println("[DEBUG] Executing statement:", stmtSQL)
_, err := db.ExecContext(ctx, stmtSQL)
if err != nil {
return fmt.Errorf("failed executing SQL: %w", err)
Expand Down Expand Up @@ -142,7 +142,7 @@ func ReadDefaultRoles(ctx context.Context, d *schema.ResourceData, meta interfac

stmtSQL := "SELECT default_role_user FROM mysql.default_roles WHERE user = ? AND host = ?"

log.Println("Executing statement:", stmtSQL)
log.Println("[DEBUG] Executing statement:", stmtSQL)

rows, err := db.QueryContext(ctx, stmtSQL, d.Get("user").(string), d.Get("host").(string))
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions mysql/resource_default_roles_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func testAccDefaultRoles(rn string, roles ...string) resource.TestCheckFunc {
}

stmtSQL := fmt.Sprintf("SELECT default_role_user from mysql.default_roles where CONCAT(user, '@', host) = '%s'", rs.Primary.ID)
log.Println("Executing statement:", stmtSQL)
log.Println("[DEBUG] Executing statement:", stmtSQL)
rows, err := db.Query(stmtSQL)
if err != nil {
return fmt.Errorf("error reading user default roles: %w", err)
Expand Down Expand Up @@ -129,7 +129,7 @@ func testAccDefaultRolesCheckDestroy(s *terraform.State) error {
}

stmtSQL := fmt.Sprintf("SELECT count(*) FROM mysql.default_roles WHERE CONCAT(user, '@', host) = '%s'", rs.Primary.ID)
log.Println("Executing statement:", stmtSQL)
log.Println("[DEBUG] Executing statement:", stmtSQL)
var count int
err := db.QueryRow(stmtSQL).Scan(&count)
if err != nil {
Expand Down
47 changes: 24 additions & 23 deletions mysql/resource_grant.go
Original file line number Diff line number Diff line change
Expand Up @@ -522,15 +522,15 @@ func CreateGrant(ctx context.Context, d *schema.ResourceData, meta interface{})
return diag.Errorf("failed showing grants: %v", err)
}
if conflictingGrant != nil {
return diag.Errorf("user/role %s already has grant %v - ", grant.GetUserOrRole(), conflictingGrant)
return diag.Errorf("user/role %#v already has grant %v - ", grant.GetUserOrRole(), conflictingGrant)
}

stmtSQL := grant.SQLGrantStatement()

log.Println("Executing statement:", stmtSQL)
log.Println("[DEBUG] Executing statement:", stmtSQL)
_, err = db.ExecContext(ctx, stmtSQL)
if err != nil {
return diag.Errorf("Error running SQL (%s): %s", stmtSQL, err)
return diag.Errorf("Error running SQL (%v): %v", stmtSQL, err)
}

d.SetId(grant.GetId())
Expand All @@ -553,7 +553,7 @@ func ReadGrant(ctx context.Context, d *schema.ResourceData, meta interface{}) di
return diag.Errorf("ReadGrant - getting all grants failed: %v", err)
}
if grantFromDb == nil {
log.Printf("[WARN] GRANT not found for %s - removing from state", grantFromTf.GetUserOrRole())
log.Printf("[WARN] GRANT not found for %#v - removing from state", grantFromTf.GetUserOrRole())
d.SetId("")
return nil
}
Expand Down Expand Up @@ -609,7 +609,7 @@ func updatePrivileges(ctx context.Context, db *sql.DB, d *schema.ResourceData, g
return fmt.Errorf("grant does not support partial privilege revokes")
}
sqlCommand := partialRevoker.SQLPartialRevokePrivilegesStatement(privsToRevoke)
log.Printf("[DEBUG] SQL: %s", sqlCommand)
log.Printf("[DEBUG] SQL for partial revoke: %s", sqlCommand)

if _, err := db.ExecContext(ctx, sqlCommand); err != nil {
return err
Expand All @@ -619,7 +619,7 @@ func updatePrivileges(ctx context.Context, db *sql.DB, d *schema.ResourceData, g
// Do a full grant if anything has been added
if len(grantIfs) > 0 {
sqlCommand := grant.SQLGrantStatement()
log.Printf("[DEBUG] SQL: %s", sqlCommand)
log.Printf("[DEBUG] SQL to re-grant privileges: %s", sqlCommand)

if _, err := db.ExecContext(ctx, sqlCommand); err != nil {
return err
Expand All @@ -646,7 +646,7 @@ func DeleteGrant(ctx context.Context, d *schema.ResourceData, meta interface{})
defer grantCreateMutex.Unlock(grant.GetUserOrRole().IDString())

sqlStatement := grant.SQLRevokeStatement()
log.Printf("[DEBUG] SQL: %s", sqlStatement)
log.Printf("[DEBUG] SQL to delete grant: %s", sqlStatement)
_, err = db.ExecContext(ctx, sqlStatement)
if err != nil {
if !isNonExistingGrant(err) {
Expand Down Expand Up @@ -696,12 +696,12 @@ func ImportGrant(ctx context.Context, d *schema.ResourceData, meta interface{})

db, err := getDatabaseFromMeta(ctx, meta)
if err != nil {
return nil, fmt.Errorf("Got error while getting database from meta: %w", err)
return nil, fmt.Errorf("got error while getting database from meta: %w", err)
}

grants, err := showUserGrants(ctx, db, userOrRole)
if err != nil {
return nil, fmt.Errorf("Failed to showUserGrants in import: %w", err)
return nil, fmt.Errorf("failed to showUserGrants in import: %w", err)
}
for _, foundGrant := range grants {
if grantsConflict(desiredGrant, foundGrant) {
Expand All @@ -711,7 +711,7 @@ func ImportGrant(ctx context.Context, d *schema.ResourceData, meta interface{})
}
}

return nil, fmt.Errorf("Failed to find the grant to import: %v -- found %v", userHostDatabaseTable, grants)
return nil, fmt.Errorf("failed to find the grant to import: %v -- found %#v", userHostDatabaseTable, grants)
}

// setDataFromGrant copies the values from MySQLGrant to the schema.ResourceData
Expand Down Expand Up @@ -776,7 +776,7 @@ func combineGrants(grantA MySQLGrant, grantB MySQLGrant) (MySQLGrant, error) {
// Check if the grants cover the same user, table, database
// If not, throw an error because they are unmergeable
if !grantsConflict(grantA, grantB) {
return nil, fmt.Errorf("Unable to combine MySQLGrant %s with %s because they don't cover the same table/database/user", grantA, grantB)
return nil, fmt.Errorf("unable to combine MySQLGrant %s with %s because they don't cover the same table/database/user", grantA, grantB)
}

// We can combine grants with privileges
Expand All @@ -795,7 +795,7 @@ func combineGrants(grantA MySQLGrant, grantB MySQLGrant) (MySQLGrant, error) {
return grantA, nil
}

return nil, fmt.Errorf("Unable to combine MySQLGrant %s of type %T with %s of type %T", grantA, grantA, grantB, grantB)
return nil, fmt.Errorf("unable to combine MySQLGrant %s of type %T with %s of type %T", grantA, grantA, grantB, grantB)
}

func getMatchingGrant(ctx context.Context, db *sql.DB, desiredGrant MySQLGrant) (MySQLGrant, error) {
Expand All @@ -809,6 +809,7 @@ func getMatchingGrant(ctx context.Context, db *sql.DB, desiredGrant MySQLGrant)
// Check if the grants cover the same user, table, database
// If not, continue
if !grantsConflict(desiredGrant, dbGrant) {
log.Printf("[DEBUG] Skipping grant %#v as it doesn't match %#v", dbGrant, desiredGrant)
continue
}

Expand All @@ -817,7 +818,7 @@ func getMatchingGrant(ctx context.Context, db *sql.DB, desiredGrant MySQLGrant)
if result != nil {
result, err = combineGrants(result, dbGrant)
if err != nil {
return nil, fmt.Errorf("Failed to combine grants in getMatchingGrant: %w", err)
return nil, fmt.Errorf("failed to combine grants in getMatchingGrant: %w", err)
}
} else {
result = dbGrant
Expand Down Expand Up @@ -894,12 +895,12 @@ func parseGrantFromRow(grantStr string) (MySQLGrant, error) {

userOrRole, err := parseUserOrRoleFromRow(procedureMatches[4])
if err != nil {
return nil, fmt.Errorf("Failed to parseUserOrRole for procedure grant: %w", err)
return nil, fmt.Errorf("failed to parseUserOrRole for procedure grant: %w", err)
}

database, callable, err := parseDatabaseQualifiedObject(procedureMatches[3])
if err != nil {
return nil, fmt.Errorf("Failed to parseDatabaseQualifiedObject for procedure grant: %w", err)
return nil, fmt.Errorf("failed to parseDatabaseQualifiedObject for procedure grant: %w", err)
}

grant := &ProcedurePrivilegeGrant{
Expand All @@ -911,7 +912,7 @@ func parseGrantFromRow(grantStr string) (MySQLGrant, error) {
UserOrRole: *userOrRole,
TLSOption: tlsOption,
}
log.Printf("[DEBUG] Got: %s, parsed grant is %s: %v", grantStr, reflect.TypeOf(grant), grant)
log.Printf("[DEBUG] Got procedure parsed grant: %s, parsed grant is %s: %v", grantStr, reflect.TypeOf(grant), grant)
return grant, nil
} else if tableMatches := tableGrantRegex.FindStringSubmatch(grantStr); len(tableMatches) == 4 {
privsStr := tableMatches[1]
Expand All @@ -925,12 +926,12 @@ func parseGrantFromRow(grantStr string) (MySQLGrant, error) {

userOrRole, err := parseUserOrRoleFromRow(tableMatches[3])
if err != nil {
return nil, fmt.Errorf("Failed to parseUserOrRole for table grant: %w", err)
return nil, fmt.Errorf("failed to parseUserOrRole for table grant: %w", err)
}

database, table, err := parseDatabaseQualifiedObject(tableMatches[2])
if err != nil {
return nil, fmt.Errorf("Failed to parseDatabaseQualifiedObject for table grant: %w", err)
return nil, fmt.Errorf("failed to parseDatabaseQualifiedObject for table grant: %w", err)
}

grant := &TablePrivilegeGrant{
Expand All @@ -941,7 +942,7 @@ func parseGrantFromRow(grantStr string) (MySQLGrant, error) {
UserOrRole: *userOrRole,
TLSOption: tlsOption,
}
log.Printf("[DEBUG] Got: %s, parsed grant is %s: %v", grantStr, reflect.TypeOf(grant), grant)
log.Printf("[DEBUG] Got table parsed grant: %s, parsed grant is %s: %v", grantStr, reflect.TypeOf(grant), grant)
return grant, nil
} else if roleMatches := roleGrantRegex.FindStringSubmatch(grantStr); len(roleMatches) == 3 {
rolesStart := strings.Split(roleMatches[1], ",")
Expand All @@ -953,7 +954,7 @@ func parseGrantFromRow(grantStr string) (MySQLGrant, error) {

userOrRole, err := parseUserOrRoleFromRow(roleMatches[2])
if err != nil {
return nil, fmt.Errorf("Failed to parseUserOrRole for role grant: %w", err)
return nil, fmt.Errorf("failed to parseUserOrRole for role grant: %w", err)
}

grant := &RoleGrant{
Expand All @@ -974,7 +975,7 @@ func showUserGrants(ctx context.Context, db *sql.DB, userOrRole UserOrRole) ([]M
grants := []MySQLGrant{}

sqlStatement := fmt.Sprintf("SHOW GRANTS FOR %s", userOrRole.SQLString())
log.Printf("[DEBUG] SQL: %s", sqlStatement)
log.Printf("[DEBUG] SQL to show grants: %s", sqlStatement)
rows, err := db.QueryContext(ctx, sqlStatement)

if isNonExistingGrant(err) {
Expand All @@ -996,7 +997,7 @@ func showUserGrants(ctx context.Context, db *sql.DB, userOrRole UserOrRole) ([]M

parsedGrant, err := parseGrantFromRow(rawGrant)
if err != nil {
return nil, fmt.Errorf("Failed to parseGrantFromRow: %w", err)
return nil, fmt.Errorf("failed to parseGrantFromRow: %w", err)
}
if parsedGrant == nil {
continue
Expand All @@ -1012,7 +1013,7 @@ func showUserGrants(ctx context.Context, db *sql.DB, userOrRole UserOrRole) ([]M
grants = append(grants, parsedGrant)

}
log.Printf("[DEBUG] Parsed grants are: %s", grants)
log.Printf("[DEBUG] Parsed grants are: %#v", grants)
return grants, nil
}

Expand Down
8 changes: 4 additions & 4 deletions mysql/resource_rds_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func CreateRDSConfig(ctx context.Context, d *schema.ResourceData, meta interface
}

for _, stmtSQL := range RDSConfigSQL(d) {
log.Println("Executing statement:", stmtSQL)
log.Println("[DEBUG] Executing statement:", stmtSQL)

_, err = db.ExecContext(ctx, stmtSQL)
if err != nil {
Expand All @@ -67,7 +67,7 @@ func UpdateRDSConfig(ctx context.Context, d *schema.ResourceData, meta interface
}

for _, stmtSQL := range RDSConfigSQL(d) {
log.Println("Executing statement:", stmtSQL)
log.Println("[DEBUG] Executing statement:", stmtSQL)

_, err = db.ExecContext(ctx, stmtSQL)
if err != nil {
Expand All @@ -86,7 +86,7 @@ func ReadRDSConfig(ctx context.Context, d *schema.ResourceData, meta interface{}

stmtSQL := "call mysql.rds_show_configuration"

log.Println("Executing query:", stmtSQL)
log.Println("[DEBUG] Executing query:", stmtSQL)
rows, err := db.QueryContext(ctx, stmtSQL)
if err != nil {
return diag.Errorf("Error reading RDS config from DB: %v", err)
Expand Down Expand Up @@ -138,7 +138,7 @@ func DeleteRDSConfig(ctx context.Context, d *schema.ResourceData, meta interface

stmtsSQL := []string{"call mysql.rds_set_configuration('binlog retention hours', NULL)", "call mysql.rds_set_configuration('target delay', 0)"}
for _, stmtSQL := range stmtsSQL {
log.Println("Executing statement:", stmtSQL)
log.Println("[DEBUG] Executing statement:", stmtSQL)

_, err = db.ExecContext(ctx, stmtSQL)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion mysql/resource_rds_config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func testAccRDSCheckDestroy() resource.TestCheckFunc {

stmtSQL := "call mysql.rds_show_configuration"

log.Println("Executing query:", stmtSQL)
log.Println("[DEBUG] Executing query:", stmtSQL)
rows, err := db.QueryContext(ctx, stmtSQL)
if err != nil {
return err
Expand Down
4 changes: 2 additions & 2 deletions mysql/resource_sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func CreateSql(ctx context.Context, d *schema.ResourceData, meta interface{}) di
name := d.Get("name").(string)
createSql := d.Get("create_sql").(string)

log.Println("Executing SQL", createSql)
log.Println("[DEBUG] Executing SQL", createSql)

_, err = db.ExecContext(ctx, createSql)
if err != nil {
Expand All @@ -65,7 +65,7 @@ func DeleteSql(ctx context.Context, d *schema.ResourceData, meta interface{}) di
}
deleteSql := d.Get("delete_sql").(string)

log.Println("Executing SQL:", deleteSql)
log.Println("[DEBUG] Executing SQL:", deleteSql)

_, err = db.ExecContext(ctx, deleteSql)
if err != nil {
Expand Down
14 changes: 7 additions & 7 deletions mysql/resource_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ func CreateUser(ctx context.Context, d *schema.ResourceData, meta interface{}) d
}
}

log.Println("Executing statement:", stmtSQL)
log.Println("[DEBUG] Executing statement:", stmtSQL)
_, err = db.ExecContext(ctx, stmtSQL)
if err != nil {
return diag.Errorf("failed executing SQL: %v", err)
Expand All @@ -230,7 +230,7 @@ func CreateUser(ctx context.Context, d *schema.ResourceData, meta interface{}) d
d.SetId(user)

if updateStmtSql != "" {
log.Println("Executing statement:", updateStmtSql)
log.Println("[DEBUG] Executing statement:", updateStmtSql)
_, err = db.ExecContext(ctx, updateStmtSql)
if err != nil {
d.Set("tls_option", "")
Expand Down Expand Up @@ -279,7 +279,7 @@ func UpdateUser(ctx context.Context, d *schema.ResourceData, meta interface{}) d
authString,
d.Get("tls_option").(string))

log.Println("Executing query:", stmtSQL)
log.Println("[DEBUG] Executing query:", stmtSQL)
_, err := db.ExecContext(ctx, stmtSQL)
if err != nil {
return diag.Errorf("failed running query: %v", err)
Expand Down Expand Up @@ -310,7 +310,7 @@ func UpdateUser(ctx context.Context, d *schema.ResourceData, meta interface{}) d
return diag.Errorf("failed getting change password statement: %v", err)
}

log.Println("Executing query:", stmtSQL)
log.Println("[DEBUG] Executing query:", stmtSQL)
_, err = db.ExecContext(ctx, stmtSQL,
d.Get("user").(string),
d.Get("host").(string),
Expand All @@ -329,7 +329,7 @@ func UpdateUser(ctx context.Context, d *schema.ResourceData, meta interface{}) d
d.Get("host").(string),
d.Get("tls_option").(string))

log.Println("Executing query:", stmtSQL)
log.Println("[DEBUG] Executing query:", stmtSQL)
_, err := db.ExecContext(ctx, stmtSQL)
if err != nil {
return diag.Errorf("failed setting require tls option: %v", err)
Expand Down Expand Up @@ -421,7 +421,7 @@ func ReadUser(ctx context.Context, d *schema.ResourceData, meta interface{}) dia
stmtSQL := fmt.Sprintf("SELECT USER FROM mysql.user WHERE USER='%s'",
d.Get("user").(string))

log.Println("Executing statement:", stmtSQL)
log.Println("[DEBUG] Executing statement:", stmtSQL)

rows, err := db.QueryContext(ctx, stmtSQL)
if err != nil {
Expand All @@ -448,7 +448,7 @@ func DeleteUser(ctx context.Context, d *schema.ResourceData, meta interface{}) d

stmtSQL := fmt.Sprintf("DROP USER ?@?")

log.Println("Executing statement:", stmtSQL)
log.Println("[DEBUG] Executing statement:", stmtSQL)

_, err = db.ExecContext(ctx, stmtSQL,
d.Get("user").(string),
Expand Down
Loading

0 comments on commit cf05886

Please sign in to comment.