Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.iceberg.spark.extensions;

import java.sql.Timestamp;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import org.apache.iceberg.AssertHelpers;
import org.apache.iceberg.Snapshot;
import org.apache.iceberg.Table;
import org.apache.iceberg.exceptions.ValidationException;
import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
import org.apache.spark.sql.AnalysisException;
import org.apache.spark.sql.catalyst.analysis.NoSuchProcedureException;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;

import static org.apache.iceberg.TableProperties.GC_ENABLED;

public class TestExpireSnapshotsProcedure extends SparkExtensionsTestBase {

public TestExpireSnapshotsProcedure(String catalogName, String implementation, Map<String, String> config) {
super(catalogName, implementation, config);
}

@After
public void removeTables() {
sql("DROP TABLE IF EXISTS %s", tableName);
}

@Test
public void testExpireSnapshotsInEmptyTable() {
sql("CREATE TABLE %s (id bigint NOT NULL, data string) USING iceberg", tableName);

List<Object[]> output = sql(
"CALL %s.system.expire_snapshots('%s', '%s')",
catalogName, tableIdent.namespace(), tableIdent.name());
assertEquals("Should not delete any files", ImmutableList.of(row(0L, 0L, 0L)), output);
}

@Test
public void testExpireSnapshotsUsingPositionalArgs() {
sql("CREATE TABLE %s (id bigint NOT NULL, data string) USING iceberg", tableName);
sql("INSERT INTO TABLE %s VALUES (1, 'a')", tableName);

Table table = validationCatalog.loadTable(tableIdent);
Snapshot firstSnapshot = table.currentSnapshot();

waitUntilAfter(firstSnapshot.timestampMillis());

sql("INSERT INTO TABLE %s VALUES (2, 'b')", tableName);

table.refresh();

Snapshot secondSnapshot = table.currentSnapshot();
Timestamp secondSnapshotTimestamp = Timestamp.from(Instant.ofEpochMilli(secondSnapshot.timestampMillis()));

Assert.assertEquals("Should be 2 snapshots", 2, Iterables.size(table.snapshots()));

// expire without retainLast param
List<Object[]> output1 = sql(
"CALL %s.system.expire_snapshots('%s', '%s', TIMESTAMP '%s')",
catalogName, tableIdent.namespace(), tableIdent.name(), secondSnapshotTimestamp);
assertEquals("Procedure output must match",
ImmutableList.of(row(0L, 0L, 1L)),
output1);

table.refresh();

Assert.assertEquals("Should expire one snapshot", 1, Iterables.size(table.snapshots()));

sql("INSERT OVERWRITE %s VALUES (3, 'c')", tableName);
sql("INSERT INTO TABLE %s VALUES (4, 'd')", tableName);
assertEquals("Should have expected rows",
ImmutableList.of(row(3L, "c"), row(4L, "d")),
sql("SELECT * FROM %s ORDER BY id", tableName));

table.refresh();

waitUntilAfter(table.currentSnapshot().timestampMillis());

Timestamp currentTimestamp = Timestamp.from(Instant.ofEpochMilli(System.currentTimeMillis()));

Assert.assertEquals("Should be 3 snapshots", 3, Iterables.size(table.snapshots()));

// expire with retainLast param
List<Object[]> output = sql(
"CALL %s.system.expire_snapshots('%s', '%s', TIMESTAMP '%s', 2)",
catalogName, tableIdent.namespace(), tableIdent.name(), currentTimestamp);
assertEquals("Procedure output must match",
ImmutableList.of(row(2L, 2L, 1L)),
output);
}

@Test
public void testExpireSnapshotUsingNamedArgs() {
sql("CREATE TABLE %s (id bigint NOT NULL, data string) USING iceberg", tableName);

sql("INSERT INTO TABLE %s VALUES (1, 'a')", tableName);
sql("INSERT INTO TABLE %s VALUES (2, 'b')", tableName);

Table table = validationCatalog.loadTable(tableIdent);

Assert.assertEquals("Should be 2 snapshots", 2, Iterables.size(table.snapshots()));

waitUntilAfter(table.currentSnapshot().timestampMillis());

Timestamp currentTimestamp = Timestamp.from(Instant.ofEpochMilli(System.currentTimeMillis()));

List<Object[]> output = sql(
"CALL %s.system.expire_snapshots(" +
"older_than => TIMESTAMP '%s'," +
"namespace => '%s'," +
"table => '%s'," +
"retain_last => 1)",
catalogName, currentTimestamp, tableIdent.namespace(), tableIdent.name());
assertEquals("Procedure output must match",
ImmutableList.of(row(0L, 0L, 1L)),
output);
}

@Test
public void testExpireSnapshotsGCDisabled() {
sql("CREATE TABLE %s (id bigint NOT NULL, data string) USING iceberg", tableName);

sql("ALTER TABLE %s SET TBLPROPERTIES ('%s' 'false')", tableName, GC_ENABLED);

AssertHelpers.assertThrows("Should reject call",
ValidationException.class, "Cannot expire snapshots: GC is disabled",
() -> sql("CALL %s.system.expire_snapshots('%s', '%s')", catalogName,
tableIdent.namespace(), tableIdent.name()));
}

@Test
public void testInvalidExpireSnapshotsCases() {
AssertHelpers.assertThrows("Should not allow mixed args",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure we need some of the more generic checks here, like testing if named and pos args cannot be mixed

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is a bit weird but we have such checks in other procedures so I added for consistency.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds fine, It doesn't really matter since they run so quickly.

AnalysisException.class, "Named and positional arguments cannot be mixed",
() -> sql("CALL %s.system.expire_snapshots('n', table => 't')", catalogName));

AssertHelpers.assertThrows("Should not resolve procedures in arbitrary namespaces",
NoSuchProcedureException.class, "not found",
() -> sql("CALL %s.custom.expire_snapshots('n', 't')", catalogName));

AssertHelpers.assertThrows("Should reject calls without all required args",
AnalysisException.class, "Missing required parameters",
() -> sql("CALL %s.system.expire_snapshots('n')", catalogName));

AssertHelpers.assertThrows("Should reject calls with invalid arg types",
RuntimeException.class, "Couldn't parse identifier",
() -> sql("CALL %s.system.expire_snapshots('n', 2.2)", catalogName));

AssertHelpers.assertThrows("Should reject empty namespace",
IllegalArgumentException.class, "Namespace cannot be empty",
() -> sql("CALL %s.system.expire_snapshots('', 't')", catalogName));

AssertHelpers.assertThrows("Should reject empty table name",
IllegalArgumentException.class, "Table name cannot be empty",
() -> sql("CALL %s.system.expire_snapshots('n', '')", catalogName));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.iceberg.spark.procedures;

import org.apache.iceberg.actions.Actions;
import org.apache.iceberg.actions.ExpireSnapshotsAction;
import org.apache.iceberg.actions.ExpireSnapshotsActionResult;
import org.apache.iceberg.spark.procedures.SparkProcedures.ProcedureBuilder;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.catalyst.util.DateTimeUtils;
import org.apache.spark.sql.connector.catalog.TableCatalog;
import org.apache.spark.sql.connector.iceberg.catalog.ProcedureParameter;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.Metadata;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;

/**
* A procedure that expires snapshots in a table.
*
* @see Actions#expireSnapshots()
*/
public class ExpireSnapshotsProcedure extends BaseProcedure {

private static final ProcedureParameter[] PARAMETERS = new ProcedureParameter[] {
ProcedureParameter.required("namespace", DataTypes.StringType),
ProcedureParameter.required("table", DataTypes.StringType),
ProcedureParameter.optional("older_than", DataTypes.TimestampType),
ProcedureParameter.optional("retain_last", DataTypes.IntegerType)
};

private static final StructType OUTPUT_TYPE = new StructType(new StructField[]{
new StructField("deleted_data_files_count", DataTypes.LongType, true, Metadata.empty()),
new StructField("deleted_manifest_files_count", DataTypes.LongType, true, Metadata.empty()),
new StructField("deleted_manifest_lists_count", DataTypes.LongType, true, Metadata.empty())
});

public static ProcedureBuilder builder() {
return new BaseProcedure.Builder<ExpireSnapshotsProcedure>() {
@Override
protected ExpireSnapshotsProcedure doBuild() {
return new ExpireSnapshotsProcedure(tableCatalog());
}
};
}

private ExpireSnapshotsProcedure(TableCatalog tableCatalog) {
super(tableCatalog);
}

@Override
public ProcedureParameter[] parameters() {
return PARAMETERS;
}

@Override
public StructType outputType() {
return OUTPUT_TYPE;
}

@Override
public InternalRow[] call(InternalRow args) {
String namespace = args.getString(0);
String tableName = args.getString(1);
Long olderThanMillis = args.isNullAt(2) ? null : DateTimeUtils.toMillis(args.getLong(2));
Integer retainLastNum = args.isNullAt(3) ? null : args.getInt(3);

return modifyIcebergTable(namespace, tableName, table -> {
Actions actions = Actions.forTable(table);

ExpireSnapshotsAction action = actions.expireSnapshots();

if (olderThanMillis != null) {
action.expireOlderThan(olderThanMillis);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So we are going with the action default expire time? Just checking because I thougt some folks wanted that changed

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The action delegates to ExpireSnapshots table API that, in turn, respects the default table props we added recently.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah! Excellent, I forgot about that

}

if (retainLastNum != null) {
action.retainLast(retainLastNum);
}

ExpireSnapshotsActionResult result = action.execute();

InternalRow outputRow = newInternalRow(
result.dataFilesDeleted(),
result.manifestFilesDeleted(),
result.manifestListsDeleted());
return new InternalRow[]{outputRow};
});
}

@Override
public String description() {
return "ExpireSnapshotProcedure";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ private static Map<String, Supplier<ProcedureBuilder>> initProcedureBuilders() {
mapBuilder.put("cherrypick_snapshot", CherrypickSnapshotProcedure::builder);
mapBuilder.put("rewrite_manifests", RewriteManifestsProcedure::builder);
mapBuilder.put("remove_orphan_files", RemoveOrphanFilesProcedure::builder);
mapBuilder.put("expire_snapshots", ExpireSnapshotsProcedure::builder);
return mapBuilder.build();
}

Expand Down