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>

12 changes: 12 additions & 0 deletions core/src/main/java/org/zstack/core/thread/DispatchQueueImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import org.zstack.header.Constants;
import org.zstack.header.core.ExceptionSafe;
import org.zstack.header.core.ReturnValueCompletion;
import org.zstack.header.core.ThreadLocalPropagation;
import org.zstack.header.core.progress.ChainInfo;
import org.zstack.header.core.progress.PendingTaskInfo;
import org.zstack.header.core.progress.SingleFlightChainInfo;
Expand Down Expand Up @@ -235,8 +236,11 @@ public DispatchQueueImpl() {
}

private class SyncTaskFuture<T> extends AbstractFuture<T> {
private final Object[] propagatedState;

public SyncTaskFuture(SyncTask<T> task) {
super(task);
this.propagatedState = ThreadLocalPropagation.capture();
}

private SyncTask getTask() {
Expand All @@ -254,12 +258,15 @@ void run() {
return;
}

ThreadLocalPropagation.restore(propagatedState);
try {
ret = (T) getTask().call();
} catch (Throwable t) {
_logger.warn(String.format("unhandled exception happened when calling sync task[name:%s, class:%s]",
getTask().getName(), getTask().getClass().getName()), t);
exception = t;
} finally {
ThreadLocalPropagation.clear();
}

done();
Expand Down Expand Up @@ -545,9 +552,11 @@ String getSyncSignature() {

class ChainFuture extends AbstractTimeStatisticFuture {
private AtomicBoolean isNextCalled = new AtomicBoolean(false);
private final Object[] propagatedState;

public ChainFuture(ChainTask task) {
super(task);
this.propagatedState = ThreadLocalPropagation.capture();
}

ChainTask getTask() {
Expand All @@ -574,11 +583,13 @@ public void run(final SyncTaskChain chain) {
return;
}

ThreadLocalPropagation.restore(propagatedState);
try {
getTask().run(() -> {
try {
done();
} finally {
ThreadLocalPropagation.clear();
callNext(chain);
}
});
Expand All @@ -590,6 +601,7 @@ public void run(final SyncTaskChain chain) {

done();
} finally {
ThreadLocalPropagation.clear();
callNext(chain);
}
}
Expand Down
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,91 @@
package org.zstack.header.core;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
* Registry and utility for cross-thread ThreadLocal propagation.
*
* Usage pattern:
* <pre>
* // At submission time (in caller thread):
* Object[] snapshot = ThreadLocalPropagation.capture();
*
* // In worker thread, before task execution:
* ThreadLocalPropagation.restore(snapshot);
*
* // In worker thread, after task execution (finally):
* ThreadLocalPropagation.clear();
* </pre>
*
* Propagators are registered once during component startup via
* {@link #register(ThreadLocalPropagator)}.
*/
public class ThreadLocalPropagation {
private static final List<ThreadLocalPropagator> propagators = new CopyOnWriteArrayList<>();

/**
* Register a propagator. Thread-safe, typically called during component start().
*/
public static void register(ThreadLocalPropagator propagator) {
if (propagator != null && !propagators.contains(propagator)) {
propagators.add(propagator);
}
}

/**
* Unregister a propagator. Thread-safe, typically called during component stop().
*/
public static void unregister(ThreadLocalPropagator propagator) {
propagators.remove(propagator);
}

/**
* Capture state from all registered propagators.
* Called in the submitting thread.
*
* @return snapshot array (one element per propagator), never null
*/
public static Object[] capture() {
List<ThreadLocalPropagator> current = propagators;
Object[] snapshot = new Object[current.size()];
for (int i = 0; i < current.size(); i++) {
snapshot[i] = current.get(i).capture();
}
return snapshot;
}

/**
* Restore captured state in the worker thread.
* Must be called before task execution.
*
* @param snapshot the array returned by {@link #capture()}
*/
public static void restore(Object[] snapshot) {
if (snapshot == null) {
return;
}
List<ThreadLocalPropagator> current = propagators;
int len = Math.min(snapshot.length, current.size());
for (int i = 0; i < len; i++) {
current.get(i).restore(snapshot[i]);
}
}

/**
* Clear all propagated state in the worker thread.
* Must be called in a finally block after task execution.
*/
public static void clear() {
for (ThreadLocalPropagator p : propagators) {
p.clear();
}
}

/**
* @return true if any propagators are registered
*/
public static boolean hasPropagators() {
return !propagators.isEmpty();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package org.zstack.header.core;

/**
* SPI for propagating ThreadLocal state across thread boundaries.
*
* Implementations capture the current thread's state at submission time,
* restore it in the worker thread before task execution, and clear it after.
*
* Register via {@link ThreadLocalPropagation#register(ThreadLocalPropagator)}.
*/
public interface ThreadLocalPropagator {
/**
* Capture current thread's state. Called in the submitting thread.
* @return opaque state object, or null if nothing to propagate
*/
Object capture();

/**
* Restore captured state in the worker thread. Called before task execution.
* @param state the object returned by {@link #capture()}, may be null
*/
void restore(Object state);

/**
* Clear state in the worker thread. Called after task execution (in finally block).
*/
void clear();
}
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);
}
}
Loading