Skip to content
Open
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
19 changes: 19 additions & 0 deletions conf/db/upgrade/V5.5.1__schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
CREATE TABLE IF NOT EXISTS `zstack`.`ExternalTenantResourceRefVO` (
`id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`source` VARCHAR(64) NOT NULL COMMENT 'source service identifier (zcf, svcX, ...)',
`tenantId` VARCHAR(128) NOT NULL COMMENT 'external tenant identifier',
`userId` VARCHAR(128) DEFAULT NULL COMMENT 'external user identifier (optional)',
`resourceUuid` VARCHAR(32) NOT NULL COMMENT 'resource UUID',
`resourceType` VARCHAR(256) NOT NULL COMMENT 'resource type (VO SimpleName)',
`accountUuid` VARCHAR(32) NOT NULL COMMENT 'associated ZStack Account',
`lastOpDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
`createDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
INDEX idx_source_tenant (`source`, `tenantId`),
INDEX idx_source_tenant_user (`source`, `tenantId`, `userId`),
INDEX idx_resource (`resourceUuid`),
UNIQUE KEY uk_resource_source_tenant (`resourceUuid`, `source`, `tenantId`),
CONSTRAINT fk_ext_tenant_resource FOREIGN KEY (`resourceUuid`)
REFERENCES `ResourceVO`(`uuid`) ON DELETE CASCADE,
CONSTRAINT fk_ext_tenant_account FOREIGN KEY (`accountUuid`)
REFERENCES `AccountVO`(`uuid`) ON DELETE CASCADE
Comment on lines +15 to +18
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

升级脚本中的外键引用建议显式带上 zstack schema。

当前 FK 引用未带 schema,和本目录既有升级脚本约定不一致,建议统一写成 zstack.\ResourceVO`/zstack.`AccountVO``。

🛠️ 建议修复
-    CONSTRAINT fk_ext_tenant_resource FOREIGN KEY (`resourceUuid`)
-        REFERENCES `ResourceVO`(`uuid`) ON DELETE CASCADE,
-    CONSTRAINT fk_ext_tenant_account FOREIGN KEY (`accountUuid`)
-        REFERENCES `AccountVO`(`uuid`) ON DELETE CASCADE
+    CONSTRAINT `fk_ext_tenant_resource` FOREIGN KEY (`resourceUuid`)
+        REFERENCES `zstack`.`ResourceVO`(`uuid`) ON DELETE CASCADE,
+    CONSTRAINT `fk_ext_tenant_account` FOREIGN KEY (`accountUuid`)
+        REFERENCES `zstack`.`AccountVO`(`uuid`) ON DELETE CASCADE

Based on learnings: In ZStack upgrade scripts under conf/db/upgrade, schema is fixed as zstack and table references should stay schema-qualified.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
CONSTRAINT fk_ext_tenant_resource FOREIGN KEY (`resourceUuid`)
REFERENCES `ResourceVO`(`uuid`) ON DELETE CASCADE,
CONSTRAINT fk_ext_tenant_account FOREIGN KEY (`accountUuid`)
REFERENCES `AccountVO`(`uuid`) ON DELETE CASCADE
CONSTRAINT `fk_ext_tenant_resource` FOREIGN KEY (`resourceUuid`)
REFERENCES `zstack`.`ResourceVO`(`uuid`) ON DELETE CASCADE,
CONSTRAINT `fk_ext_tenant_account` FOREIGN KEY (`accountUuid`)
REFERENCES `zstack`.`AccountVO`(`uuid`) ON DELETE CASCADE
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@conf/db/upgrade/V5.5.1__schema.sql` around lines 15 - 18, 升级脚本中的外键引用未带
schema,需将 REFERENCES 目标表显式限定为 zstack 模式:在 V5.5.1__schema.sql 中把 CONSTRAINT
fk_ext_tenant_resource 的 REFERENCES `ResourceVO`(`uuid`) 改为 REFERENCES
zstack.`ResourceVO`(`uuid`),并把 CONSTRAINT fk_ext_tenant_account 的 REFERENCES
`AccountVO`(`uuid`) 改为 REFERENCES zstack.`AccountVO`(`uuid`),保持与 conf/db/upgrade
目录其它脚本的 schema-qualified 约定一致。

) ENGINE=InnoDB DEFAULT CHARSET=utf8;
16 changes: 16 additions & 0 deletions conf/springConfigXml/AccountManager.xml
Original file line number Diff line number Diff line change
Expand Up @@ -111,5 +111,21 @@
<bean id = "RoleUtils" class="org.zstack.identity.rbac.RoleUtils"/>

<bean id="AccountQuotaUpdateChecker" class="org.zstack.identity.AccountQuotaUpdateChecker"/>

<bean id="ExternalTenantResourceTracker" class="org.zstack.identity.ExternalTenantResourceTracker">
<zstack:plugin>
<zstack:extension interface="org.zstack.header.Component"/>
<zstack:extension interface="org.zstack.core.db.HardDeleteEntityExtensionPoint"/>
<zstack:extension interface="org.zstack.core.db.SoftDeleteEntityByEOExtensionPoint"/>
<zstack:extension interface="org.zstack.header.aspect.OwnedByAccountAspectHelper$ResourceOwnershipCreationNotifier"/>
</zstack:plugin>
</bean>

<bean id="ExternalTenantZQLExtension" class="org.zstack.identity.ExternalTenantZQLExtension">
<zstack:plugin>
<zstack:extension interface="org.zstack.header.zql.MarshalZQLASTTreeExtensionPoint"/>
<zstack:extension interface="org.zstack.header.zql.RestrictByExprExtensionPoint"/>
</zstack:plugin>
</bean>
</beans>

Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,28 @@
import org.zstack.header.identity.AccountResourceRefVO;
import org.zstack.header.identity.OwnedByAccount;
import org.zstack.header.vo.ResourceTypeMetadata;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;

import javax.persistence.EntityManager;

public class OwnedByAccountAspectHelper {
private static final CLogger logger = Utils.getLogger(OwnedByAccountAspectHelper.class);

// static field for resource ownership creation extension point callback
private static ResourceOwnershipCreationNotifier notifier;

// ThreadLocal to pass EntityManager from AOP context to notifier
private static final ThreadLocal<EntityManager> currentEntityManager = new ThreadLocal<>();

public static void setResourceOwnershipCreationNotifier(ResourceOwnershipCreationNotifier notifier) {
OwnedByAccountAspectHelper.notifier = notifier;
}

public static EntityManager getCurrentEntityManager() {
return currentEntityManager.get();
}

public static void createAccountResourceRefVO(OwnedByAccount oa, EntityManager entityManager, Object entity) {
AccountResourceRefVO ref = new AccountResourceRefVO();
ref.setAccountUuid(oa.getAccountUuid());
Expand All @@ -19,5 +37,26 @@ public static void createAccountResourceRefVO(OwnedByAccount oa, EntityManager e
ref.setShared(false);

entityManager.persist(ref);

// notify resource ownership creation event
if (notifier != null) {
try {
currentEntityManager.set(entityManager);
notifier.notifyResourceOwnershipCreated(ref);
} catch (Exception e) {
logger.warn(String.format("failed to notify resource ownership creation for resource[uuid:%s, type:%s]: %s",
ref.getResourceUuid(), ref.getResourceType(), e.getMessage()), e);
throw e;
} finally {
currentEntityManager.remove();
}
}
}

/**
* Resource ownership creation notifier interface to avoid circular dependency
*/
public static interface ResourceOwnershipCreationNotifier {
void notifyResourceOwnershipCreated(AccountResourceRefVO ref);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package org.zstack.header.identity;

import java.io.Serializable;

/**
* External tenant context DTO.
* Passed by external services (like ZCF, AIOS, etc.) through HTTP Headers,
* attached to SessionInventory throughout the entire request chain.
*/
public class ExternalTenantContext implements Serializable {
private static final long serialVersionUID = 1L;

// ThreadLocal used to pass current request's external tenant context at AOP level
// Set by RestServer after Header parsing, cleaned up after request completion
private static final ThreadLocal<ExternalTenantContext> current = new ThreadLocal<>();

public static void setCurrent(ExternalTenantContext ctx) {
current.set(ctx);
}

public static ExternalTenantContext getCurrent() {
return current.get();
}

public static void clearCurrent() {
current.remove();
}

private String source; // Source service identifier, such as "zcf", "svcX"
private String tenantId; // External tenant identifier
private String userId; // External user identifier (optional)

public ExternalTenantContext() {
}

public ExternalTenantContext(String source, String tenantId, String userId) {
this.source = source;
this.tenantId = tenantId;
this.userId = userId;
}

public String getSource() {
return source;
}

public void setSource(String source) {
this.source = source;
}

public String getTenantId() {
return tenantId;
}

public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}

public String getUserId() {
return userId;
}

public void setUserId(String userId) {
this.userId = userId;
}

@Override
public String toString() {
return String.format("ExternalTenantContext{source='%s', tenantId='%s', userId='%s'}", source, tenantId, userId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package org.zstack.header.identity;

/**
* External tenant Provider SPI.
* Each external service (ZCF, AIOS, etc.) implements this interface to integrate with the universal tenant resource isolation framework.
*
* The framework automatically collects all implementations through {@link org.zstack.core.componentloader.PluginRegistry}.
* Each Provider returns a unique source identifier (such as "zcf") through {@link #getSource()},
* corresponding to the HTTP Header X-Tenant-Source value.
*/
public interface ExternalTenantProvider {
/**
* Source identifier, such as "zcf", "svcX".
* Corresponds to X-Tenant-Source header value.
* Must be globally unique.
*/
String getSource();

/**
* Validate tenant context validity.
* Called after RestServer parses Header and before injecting into Session.
* Throwing an exception indicates validation failure, and the request will be rejected with HTTP 400.
* Any exception type is acceptable; non-RestException will be wrapped as 400 Bad Request by RestServer.
*
* @param ctx External tenant context (already parsed from Header)
* @throws RuntimeException if validation fails (e.g. invalid tenantId format)
*/
void validateTenant(ExternalTenantContext ctx);

/**
* Whether to track this type of resource.
* After resource creation, the framework calls this method to decide whether to write to ExternalTenantResourceRefVO.
* Returning false indicates that this resource type does not need to be associated with tenant.
* Default is true (track all resources).
*
* @param resourceType Resource type (VO SimpleName, such as "VmInstanceVO")
*/
default boolean shouldTrackResource(String resourceType) {
return true;
}

/**
* Resource binding callback (optional).
* Called after ExternalTenantResourceRefVO is written,
* Provider can use this for custom logic such as sending notifications or writing audit logs.
*
* @param ctx External tenant context
* @param resourceUuid Resource UUID
* @param resourceType Resource type (VO SimpleName)
*/
default void onResourceBound(ExternalTenantContext ctx,
String resourceUuid, String resourceType) {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package org.zstack.header.identity;

import org.zstack.header.configuration.PythonClassInventory;
import org.zstack.header.search.Inventory;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
* Inventory for ExternalTenantResourceRefVO
*/
@PythonClassInventory
@Inventory(mappingVOClass = ExternalTenantResourceRefVO.class)
public class ExternalTenantResourceRefInventory {
private long id;
private String source;
private String tenantId;
private String userId;
private String resourceUuid;
private String accountUuid;
private String resourceType;
private Timestamp createDate;
private Timestamp lastOpDate;

public ExternalTenantResourceRefInventory() {
}

public static List<ExternalTenantResourceRefInventory> valueOf(Collection<ExternalTenantResourceRefVO> vos) {
List<ExternalTenantResourceRefInventory> invs = new ArrayList<>();
for (ExternalTenantResourceRefVO vo : vos) {
invs.add(valueOf(vo));
}
return invs;
}

public static ExternalTenantResourceRefInventory valueOf(ExternalTenantResourceRefVO vo) {
return new ExternalTenantResourceRefInventory(vo);
}

public ExternalTenantResourceRefInventory(ExternalTenantResourceRefVO vo) {
this.id = vo.getId();
this.source = vo.getSource();
this.tenantId = vo.getTenantId();
this.userId = vo.getUserId();
this.resourceUuid = vo.getResourceUuid();
this.accountUuid = vo.getAccountUuid();
this.resourceType = vo.getResourceType();
this.createDate = vo.getCreateDate();
this.lastOpDate = vo.getLastOpDate();
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getSource() {
return source;
}

public void setSource(String source) {
this.source = source;
}

public String getTenantId() {
return tenantId;
}

public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}

public String getUserId() {
return userId;
}

public void setUserId(String userId) {
this.userId = userId;
}

public String getResourceUuid() {
return resourceUuid;
}

public void setResourceUuid(String resourceUuid) {
this.resourceUuid = resourceUuid;
}

public String getAccountUuid() {
return accountUuid;
}

public void setAccountUuid(String accountUuid) {
this.accountUuid = accountUuid;
}

public String getResourceType() {
return resourceType;
}

public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}

public Timestamp getCreateDate() {
return createDate;
}

public void setCreateDate(Timestamp createDate) {
this.createDate = createDate;
}

public Timestamp getLastOpDate() {
return lastOpDate;
}

public void setLastOpDate(Timestamp lastOpDate) {
this.lastOpDate = lastOpDate;
}
}
Loading