Skip to content
Closed
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
22 changes: 21 additions & 1 deletion conf/db/upgrade/V5.4.8__schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,24 @@ CREATE TABLE IF NOT EXISTS `zstack`.`ResNotifyWebhookRefVO` (
PRIMARY KEY (`uuid`),
CONSTRAINT `fk_ResNotifyWebhookRefVO_ResNotifySubscriptionVO`
FOREIGN KEY (`uuid`) REFERENCES `ResNotifySubscriptionVO`(`uuid`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

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',
`createDate` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
`lastOpDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_source_tenant_user (`source`, `tenantId`, `userId`),
INDEX idx_source_tenant_resource (`source`, `tenantId`, `resourceUuid`),
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
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1 change: 1 addition & 0 deletions conf/persistence.xml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
<class>org.zstack.header.identity.SessionVO</class>
<class>org.zstack.header.identity.AccountVO</class>
<class>org.zstack.header.identity.AccountResourceRefVO</class>
<class>org.zstack.header.identity.ExternalTenantResourceRefVO</class>
<class>org.zstack.header.identity.UserVO</class>
<class>org.zstack.header.identity.PolicyVO</class>
<class>org.zstack.header.identity.UserPolicyRefVO</class>
Expand Down
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 @@ -6,8 +6,27 @@
import org.zstack.header.vo.ResourceTypeMetadata;

import javax.persistence.EntityManager;
import java.util.Collections;
import java.util.List;

public class OwnedByAccountAspectHelper {

/**
* Extension point for receiving notifications when resource ownership is created.
* Implementations should be registered via PluginRegistry (Spring XML).
*/
public static interface ResourceOwnershipCreationNotifier {
void notifyResourceOwnershipCreated(AccountResourceRefVO ref, EntityManager entityManager);
}

// Notifiers populated by PluginRegistry; set once during Component.start() phase.
// Using static field because AOP aspects cannot participate in Spring DI.
private static volatile List<ResourceOwnershipCreationNotifier> notifiers = Collections.emptyList();

public static void setResourceOwnershipCreationNotifiers(List<ResourceOwnershipCreationNotifier> list) {
notifiers = list != null ? list : Collections.emptyList();
}

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

entityManager.persist(ref);

// Notify all registered listeners — no try-catch so exceptions propagate
// and the outer transaction rolls back, ensuring strong consistency between
// AccountResourceRefVO and ExternalTenantResourceRefVO.
// Pass the EntityManager so listeners persist within the same flush/TX context,
// avoiding nested @DeadlockAutoRestart scopes that cause unretryable rollbacks.
for (ResourceOwnershipCreationNotifier n : notifiers) {
n.notifyResourceOwnershipCreated(ref, entityManager);
}
}
}
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,52 @@
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.
*
* @param ctx External tenant context (already parsed from Header)
*/
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,122 @@
package org.zstack.header.identity;

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

import java.sql.Timestamp;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
* 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) {
return vos.stream().map(ExternalTenantResourceRefInventory::valueOf)
.collect(Collectors.toList());
}

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