TenantContainer.java 22.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
/*
 * Copyright (c) 2020 Alibaba Group Holding Limited. All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation. Alibaba designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */

package com.alibaba.tenant;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import com.alibaba.rcm.ResourceContainer;
import com.alibaba.rcm.Constraint;
import com.alibaba.rcm.internal.AbstractResourceContainer;
import static com.alibaba.tenant.TenantState.*;


/**
 * TenantContainer is a "virtual container" for a tenant of application, the
 * resource consumption of tenant such as CPU, heap is constrained by the policy
 * of this "virtual container". The thread can run in virtual container by
 * calling <code>TenantContainer.run</code>
 *
 */
public class TenantContainer {

    TenantResourceContainer resourceContainer;

    private static NativeDispatcher nd = new NativeDispatcher();

    /*
     * Used to generate the tenant id.
     */
    private static AtomicLong nextTenantID = new AtomicLong(0);

    /*
     * Used to hold the mapping from tenant id to TenantContainer object for all
     * tenants
     */
    private static Map<Long, TenantContainer> tenantContainerMap = null;

    /*
     * Holds the threads attached with this tenant container
     */
    private List<Thread> attachedThreads = new LinkedList<>();

    /*
     * Newly created threads which attach to this tenant container
     */
    private List<WeakReference<Thread>> spawnedThreads = Collections.synchronizedList(new ArrayList<>());

    /*
     * Used to contain service threads, including finalizer threads, shutdown hook threads.
     */
    private Map<Thread, Void> serviceThreads = Collections.synchronizedMap(new WeakHashMap<>());

    /*
     * the configuration of this tenant container
     */
    private TenantConfiguration configuration = null;

    /*
     * tenant state
     */
    private volatile TenantState state;

    /*
     * tenant id
     */
    private long tenantId;

96 97 98 99 100
    /*
     * address of native tenant allocation context
     */
    private long allocationContext = 0L;

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    /*
     * tenant name
     */
    private String name;

    /*
     * Used to store the system properties per tenant
     */
    private Properties props;

    /*
     * allocated memory of attached threads, which is accumulated for current tenant
     */
    private long accumulatedMemory = 0L;

    /**
     * Get total allocated memory of this tenant.
     * @return the total allocated memory of this tenant.
     */
    public synchronized long getAllocatedMemory() {
        Thread[] threads = getAttachedThreads();
        int size         = threads.length;
        long[] ids       = new long[size];
        long[] memSizes  = new long[size];

        for (int i = 0; i < size; i++) {
            ids[i] = threads[i].getId();
        }

        nd.getThreadsAllocatedMemory(ids, memSizes);

        long totalThreadsAllocatedMemory = 0;
        for (long s : memSizes) {
            totalThreadsAllocatedMemory += s;
        }
        return totalThreadsAllocatedMemory + accumulatedMemory;
    }

    /**
     * Used to track and run tenant shutdown hooks
     */
    private TenantShutdownHooks tenantShutdownHooks = new TenantShutdownHooks();

    /**
     * Sets the tenant properties to the one specified by argument.
     * @param props the properties to be set, CoW the system properties if it is null.
     */
    public void setProperties(Properties props) {
        if (props == null) {
            props = new Properties();
            Properties sysProps = System.getProperties();
            for(Object key: sysProps.keySet()) {
                props.put(key, sysProps.get(key));
            }
        }
        this.props = props;
    }

    /**
     * Gets the properties of tenant
     * @return the tenant properties
     */
    public Properties getProperties() {
        return props;
    }

    /**
     * Sets the property indicated by the specified key.
     * @param  key the name of the property.
     * @param  value the value of the property.
     * @return the previous value of the property,
     *         or null if it did not have one.
     */
    public String setProperty(String key, String value) {
        checkKey(key);
        return (String) props.setProperty(key, value);
    }

    /**
     * Gets the property indicated by the specified key.
     * @param  key  the name of the property.
     * @return the  string value of the property,
     *         or null if there is no property with that key.
     */
    public String getProperty(String key) {
        checkKey(key);
        return props.getProperty(key);
    }

    /**
     * Removes the property indicated by the specified key.
     * @param  key  the name of the property to be removed.
     * @return the  previous string value of the property,
     *         or null if there was no property with that key.
     */
    public String clearProperty(String key) {
        checkKey(key);
        return (String) props.remove(key);
    }

    private void checkKey(String key) {
        if (null == key) {
            throw new NullPointerException("key can't be null");
        }
        if ("".equals(key)) {
            throw new IllegalArgumentException("key can't be empty");
        }
    }

    //
    // Used to synchronize between destroy() and runThread()
    private ReentrantReadWriteLock destroyLock = new ReentrantReadWriteLock();


    /**
     * Destroy this tenant container and release occupied resources including memory, cpu, FD, etc.
     *
     */
    public void destroy() {
        if (TenantContainer.current() != null) {
            throw new RuntimeException("Should only call destroy() in ROOT tenant");
        }

        destroyLock.writeLock().lock();
        try {
            if (state != TenantState.STOPPING && state != TenantState.DEAD) {
                setState(TenantState.STOPPING);

                tenantContainerMap.remove(getTenantId());

                // finish all finalizers
                resourceContainer.attach();
                nd.attach(this);
                try {
                    Runtime.getRuntime().runFinalization();
                } finally {
                    nd.attach(null);
                    resourceContainer.detach();
                }

                // execute all shutdown hooks
                tenantShutdownHooks.runHooks();
            }
        } catch (Throwable t) {
            System.err.println("Exception from TenantContainer.destroy()");
            t.printStackTrace();
        } finally {
            setState(TenantState.DEAD);
            cleanUp();
            destroyLock.writeLock().unlock();
        }
    }

    /*
     * Release all native resources and Java references
     * should be the very last step of {@link #destroy()} operation.
     * If cannot kill all threads in {@link #killAllThreads()}, should do this in {@link WatchDogThread}
     *
     */
    private void cleanUp() {
261 262 263 264
        if (TenantGlobals.isHeapIsolationEnabled()) {
            nd.destroyTenantAllocationContext(allocationContext);
        }

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
        // clear references
        spawnedThreads.clear();
        attachedThreads.clear();
        tenantShutdownHooks = null;
    }

    private TenantContainer(TenantContainer parent, String name, TenantConfiguration configuration) {
        this.tenantId = nextTenantID.getAndIncrement();
        this.resourceContainer = new TenantResourceContainer(
                (parent == null ? null : parent.resourceContainer),
                this,
                configuration.getAllConstraints());
        this.name = (name == null ? "Tenant-" + getTenantId() : name);
        this.configuration = configuration;

        setState(STARTING);

        //Initialize the tenant properties.
        props = new Properties();
        props.putAll(System.getProperties());
        tenantContainerMap.put(this.tenantId, this);
286 287 288 289 290

        // Create allocation context if heap isolation enabled
        if (TenantGlobals.isHeapIsolationEnabled()) {
            nd.createTenantAllocationContext(this, configuration.getMaxHeap());
        }
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
    }

    TenantConfiguration getConfiguration() {
        return configuration;
    }

    /**
     * @return the tenant state
     */
    public TenantState getState() {
        return state;
    }

    /*
     * Set the tenant state
     * @param state used to set
     */
    void setState(TenantState state) {
        this.state = state;
    }

    /**
     * Returns the tenant' id
     * @return tenant id
     */
    public long getTenantId() {
        return tenantId;
    }

    /**
     * Returns this tenant's name.
     * @return this tenant's name.
     */
    public String getName() {
        return name;
    }

    /**
     * @return A collection of all threads attached to the container.
     */
    public synchronized Thread[] getAttachedThreads() {
        return attachedThreads.toArray(new Thread[attachedThreads.size()]);
    }

    /**
     * Get the tenant container by id
     * @param id tenant id.
     * @return the tenant specified by id, null if the id doesn't exist.
     */
    public static TenantContainer getTenantContainerById(long id) {
        checkIfTenantIsEnabled();
        return tenantContainerMap.get(id);
    }

    /**
     * Create tenant container by the configuration
     * @param configuration used to create tenant
     * @return the tenant container
     */
    public static TenantContainer create(TenantConfiguration configuration) {
        return create(TenantContainer.current(), configuration);
    }

    /**
     * Create tenant container by the configuration
     * @param parent parent tenant container
     * @param configuration used to create tenant
     * @return the tenant container
     */
    public static TenantContainer create(TenantContainer parent,
                                         TenantConfiguration configuration) {
        checkIfTenantIsEnabled();
        //parameter checking
        if (null == configuration) {
            throw new IllegalArgumentException("Failed to create tenant, illegal arguments: configuration is null");
        }

        return create(parent, null, configuration);
    }
    /**
     * Create tenant container by the name and configuration
     * @param name the tenant name
     * @param configuration used to create tenant
     * @return the tenant container
     */
    public static TenantContainer create(String name, TenantConfiguration configuration) {
        return create(TenantContainer.current(), name, configuration);
    }

    /**
     * Create tenant container by the name and configuration
     * @param parent parent tenant container
     * @param name the tenant name
     * @param configuration used to create tenant
     * @return the tenant container
     */
    public static TenantContainer create(TenantContainer parent, String name, TenantConfiguration configuration) {
        checkIfTenantIsEnabled();
        //parameter checking
        if (null == configuration) {
            throw new IllegalArgumentException("Failed to create tenant, illegal arguments: configuration is null");
        }
393

394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
        TenantContainer tc = new TenantContainer(parent, name, configuration);
        tenantContainerMap.put(tc.getTenantId(), tc);
        return tc;
    }

    /**
     * Gets the tenant id list
     * @return the tenant id list, Collections.emptyList if no tenant exists.
     */
    public static List<Long> getAllTenantIds() {
        checkIfTenantIsEnabled();
        if (null == tenantContainerMap) {
            throw new IllegalStateException("TenantContainer class is not initialized !");
        }
        if (tenantContainerMap.size() == 0) {
            return Collections.EMPTY_LIST;
        }

        return new ArrayList<>(tenantContainerMap.keySet());
    }

    /**
     * Gets the TenantContainer attached to the current thread.
     * @return The TenantContainer attached to the current thread, null if no
     *         TenantContainer is attached to the current thread.
     */
    public static TenantContainer current() {
        checkIfTenantIsEnabled();
        AbstractResourceContainer curResContainer = TenantResourceContainer.current();
        if (TenantResourceContainer.root() == curResContainer) {
            return null;
        }
        assert curResContainer instanceof TenantResourceContainer;
        return ((TenantResourceContainer)curResContainer).getTenant();
    }

    /**
     * Gets the cpu time consumed by this tenant
     * @return the cpu time used by this tenant, 0 if tenant cpu throttling or accounting feature is disabled.
     */
    public long getProcessCpuTime() {
        if (!TenantGlobals.isCpuAccountingEnabled()) {
            throw new IllegalStateException("-XX:+TenantCpuAccounting is not enabled");
        }
        long cpuTime = 0;
        return cpuTime;
    }

442 443 444 445 446 447 448 449 450 451 452 453
    /**
     * Gets the heap space occupied by this tenant
     * @return heap space occupied by this tenant, 0 if tenant heap isolation is disabled.
     * @throws IllegalStateException if -XX:+TenantHeapIsolation is not enabled.
     */
    public long getOccupiedMemory() {
        if (!TenantGlobals.isHeapIsolationEnabled()) {
            throw new IllegalStateException("-XX:+TenantHeapIsolation is not enabled");
        }
        return nd.getTenantOccupiedMemory(allocationContext);
    }

454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    /**
     * Runs the code in the target tenant container
     * @param task the code to run
     */
    public void run(Runnable task) throws TenantException {
        if (getState() == DEAD || getState() == STOPPING) {
            throw new TenantException("Tenant is dead");
        }
        TenantContainer container = current();
        assert container != null;
        if (container == this) {
            task.run();
        } else {
            if (container != null) {
                throw new TenantException("must be in root container " +
                        "before running into non-root container.");
            }
            attach();
            try {
                task.run();
            } finally {
                detach();
            }
        }
    }

    /*
     * Get accumulatedMemory value of current thread
     */
    private long getThreadAllocatedMemory() {
        long[] memSizes = new long[1];
        nd.getThreadsAllocatedMemory(null, memSizes);
        return memSizes[0];
    }

    private void attach() {
        // This is the first thread which runs in this tenant container
        if (getState() == TenantState.STARTING) {
            // move the tenant state to RUNNING
            this.setState(TenantState.RUNNING);
        }

        Thread curThread = Thread.currentThread();

        long curAllocBytes = getThreadAllocatedMemory();

        synchronized (this) {
            attachedThreads.add(curThread);

            accumulatedMemory -= curAllocBytes;

            resourceContainer.attach();

            nd.attach(this);
        }
    }

    private void detach() {
        Thread curThread = Thread.currentThread();

        long curAllocBytes = getThreadAllocatedMemory();

        synchronized (this) {
            nd.attach(null);

            resourceContainer.detach();

            attachedThreads.remove(curThread);

            accumulatedMemory += curAllocBytes;
        }
    }

    /*
     * Check if the tenant feature is enabled.
     */
    private static void checkIfTenantIsEnabled() {
        if (!TenantGlobals.isTenantEnabled()) {
            throw new UnsupportedOperationException("The multi-tenant feature is not enabled!");
        }
    }

    /*
     * Invoked by the VM to run a thread in multi-tenant mode.
     *
     * NOTE: please ensure relevant logic has been fully understood before changing any code
     *
     * @throws TenantException
     */
    private void runThread(final Thread thread) throws TenantException {
        if (destroyLock.readLock().tryLock()) {
            if (getState() != STOPPING && getState() != DEAD) {
                spawnedThreads.add(new WeakReference<>(thread));
                this.run(() -> {
                    destroyLock.readLock().unlock();
                    thread.run();
                });
            } else {
                destroyLock.readLock().unlock();
            }

            // try to clean up once
            if (destroyLock.readLock().tryLock()) {
                if (getState() != STOPPING && getState() != DEAD) {
                    spawnedThreads.removeIf(ref -> ref.get() == null || ref.get() == thread);
                }
                destroyLock.readLock().unlock();
            }
        } else {
            // shutdown in progress
            if (serviceThreads.containsKey(thread)) {
                // attach to current thread to run without registering
                resourceContainer.attach();
                nd.attach(this);
                try {
                    thread.run();
                } finally {
                    nd.attach(null);
                    resourceContainer.detach();
                    removeServiceThread(thread);
                }
            }
        }
    }

    /*
     * Initialize the TenantContainer class, called after System.initializeSystemClass by VM.
     */
    private static void initializeTenantContainerClass() {
        //Initialize this field after the system is booted.
        tenantContainerMap = Collections.synchronizedMap(new HashMap());

        try {
            // force initialization of TenantConfiguration
            Class.forName("com.alibaba.tenant.TenantConfiguration");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

594 595 596 597 598 599 600 601 602 603 604 605 606
    /**
     * Retrieve the tenant container where <code>obj</code> is allocated in
     * @param obj    object to be searched
     * @return       TenantContainer object whose memory space contains <code>obj</code>,
     *               or null if ROOT tenant container
     */
    public static TenantContainer containerOf(Object obj) {
        if (!TenantGlobals.isHeapIsolationEnabled()) {
            throw new UnsupportedOperationException("containerOf() only works with -XX:+TenantHeapIsolation");
        }
        return obj != null ? nd.containerOf(obj) : null;
    }

607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
    /**
     * Runs {@code Supplier.get} in the root tenant.
     * @param supplier target used to call
     * @return the result of {@code Supplier.get}
     */
    public static <T> T primitiveRunInRoot(Supplier<T> supplier) {
        // thread is already in root tenant.
        if(null == TenantContainer.current()) {
            return supplier.get();
        } else{
            TenantContainer tenant = TenantContainer.current();
            //Force to root tenant.
            tenant.resourceContainer.detach();
            nd.attach(null);
            try {
                T t = supplier.get();
                return t;
            } finally {
                nd.attach(tenant);
                tenant.resourceContainer.attach();
            }
        }
    }

    /**
     * Runs a block of code in the root tenant.
     * @param runnable the code to run
     */
    public static void primitiveRunInRoot(Runnable runnable) {
        primitiveRunInRoot(() -> {
            runnable.run();
            return null;
        });
    }

    /**
     * Register a new tenant shutdown hook.
     * When the tenant begins its destroy it will
     * start all registered shutdown hooks in some unspecified order and let
     * them run concurrently.
     * @param   hook
     *          An initialized but unstarted <tt>{@link Thread}</tt> object
     */
    public void addShutdownHook(Thread hook) {
        addServiceThread(hook);
        tenantShutdownHooks.add(hook);
    }

    /**
     * De-registers a previously-registered tenant shutdown hook.
     * @param hook the hook to remove
     * @return true if the specified hook had previously been
     * registered and was successfully de-registered, false
     * otherwise.
     */
    public boolean removeShutdownHook(Thread hook) {
        removeServiceThread(hook);
        return tenantShutdownHooks.remove(hook);
    }

    // add a thread to the service thread list
    private void addServiceThread(Thread thread) {
        if (thread != null) {
            serviceThreads.put(thread, null);
        }
    }

    // remove a thread from the service thread list
    private void removeServiceThread(Thread thread) {
        serviceThreads.remove(thread);
    }

    /**
     * Try to modify resource limit of current tenant,
     * for resource whose limit cannot be changed after creation of {@code TenantContainer}, its limit will be ignored.
     * @param config  new TenantConfiguration to
     */
    public void update(TenantConfiguration config) {
        for (Constraint constraint : config.getAllConstraints()) {
            updateConstraint(constraint);
        }
    }

    void updateConstraint(Constraint constraint) {
        resourceContainer.updateConstraint(constraint);
        getConfiguration().setConstraint(constraint);
    }

    /**
     * @return {@code ResourceContainer} of this tenant
     */
    public ResourceContainer getResourceContainer() {
        return resourceContainer;
    }
}