id
stringlengths
7
14
text
stringlengths
1
106k
206414745_1842
@Override public OperationResult execute(final MessageFrame frame, final EVM evm) { final UInt256 key = UInt256.fromBytes(frame.popStackItem()); final UInt256 value = UInt256.fromBytes(frame.popStackItem()); final MutableAccount account = frame.getWorldState().getAccount(frame.getRecipientAddress()).getMutable(); if (account == null) { return ILLEGAL_STATE_CHANGE; } final Address address = account.getAddress(); final boolean slotIsWarm = frame.warmUpStorage(address, key.toBytes()); final Gas cost = gasCalculator() .calculateStorageCost(account, key, value) .plus(slotIsWarm ? Gas.ZERO : gasCalculator().getColdSloadCost()); final Optional<Gas> optionalCost = Optional.of(cost); final Gas remainingGas = frame.getRemainingGas(); if (frame.isStatic()) { return new OperationResult( optionalCost, Optional.of(ExceptionalHaltReason.ILLEGAL_STATE_CHANGE)); } else if (remainingGas.compareTo(cost) < 0) { return new OperationResult(optionalCost, Optional.of(ExceptionalHaltReason.INSUFFICIENT_GAS)); } else if (remainingGas.compareTo(minumumGasRemaining) <= 0) { return new OperationResult( Optional.of(minumumGasRemaining), Optional.of(ExceptionalHaltReason.INSUFFICIENT_GAS)); } // Increment the refund counter. frame.incrementGasRefund(gasCalculator().calculateStorageRefundAmount(account, key, value)); account.setStorageValue(key, value); frame.storageWasUpdated(key, value.toBytes()); return new OperationResult(optionalCost, Optional.empty()); }
206414745_1843
@Override protected Address targetContractAddress(final MessageFrame frame) { final Address sender = frame.getRecipientAddress(); final UInt256 offset = UInt256.fromBytes(frame.getStackItem(1)); final UInt256 length = UInt256.fromBytes(frame.getStackItem(2)); final Bytes32 salt = frame.getStackItem(3); final Bytes initCode = frame.readMemory(offset, length); final Hash hash = Hash.hash(Bytes.concatenate(PREFIX, sender, salt, Hash.hash(initCode))); final Address address = Address.extract(hash); frame.warmUpAddress(address); return address; }
206414745_1844
@Override public OperationResult execute(final MessageFrame frame, final EVM evm) { final UInt256 from = UInt256.fromBytes(frame.popStackItem()); final UInt256 length = UInt256.fromBytes(frame.popStackItem()); final Gas cost = gasCalculator().memoryExpansionGasCost(frame, from, length); final Optional<Gas> optionalCost = Optional.of(cost); if (frame.getRemainingGas().compareTo(cost) < 0) { return new OperationResult(optionalCost, Optional.of(ExceptionalHaltReason.INSUFFICIENT_GAS)); } final Bytes reason = frame.readMemory(from, length); frame.setOutputData(reason); frame.setRevertReason(reason); frame.setState(MessageFrame.State.REVERT); return new OperationResult(optionalCost, Optional.empty()); }
206414745_1845
public Hash getBlockHash(final long blockNumber) { final Hash cachedHash = hashByNumber.get(blockNumber); if (cachedHash != null) { return cachedHash; } while (searchStartHeader != null && searchStartHeader.getNumber() - 1 > blockNumber) { searchStartHeader = blockchain.getBlockHeader(searchStartHeader.getParentHash()).orElse(null); if (searchStartHeader != null) { hashByNumber.put(searchStartHeader.getNumber() - 1, searchStartHeader.getParentHash()); } } return hashByNumber.getOrDefault(blockNumber, Hash.ZERO); }
206414745_1846
public Hash getBlockHash(final long blockNumber) { final Hash cachedHash = hashByNumber.get(blockNumber); if (cachedHash != null) { return cachedHash; } while (searchStartHeader != null && searchStartHeader.getNumber() - 1 > blockNumber) { searchStartHeader = blockchain.getBlockHeader(searchStartHeader.getParentHash()).orElse(null); if (searchStartHeader != null) { hashByNumber.put(searchStartHeader.getNumber() - 1, searchStartHeader.getParentHash()); } } return hashByNumber.getOrDefault(blockNumber, Hash.ZERO); }
206414745_1847
@VisibleForTesting Operation operationAtOffset(final Code code, final int contractAccountVersion, final int offset) { final Bytes bytecode = code.getBytes(); // If the length of the program code is shorter than the required offset, halt execution. if (offset >= bytecode.size()) { return endOfScriptStop; } final byte opcode = bytecode.get(offset); final Operation operation = operations.get(opcode, contractAccountVersion); if (operation == null) { return new InvalidOperation(opcode, null); } else { return operation; } }
206414745_1848
@VisibleForTesting Operation operationAtOffset(final Code code, final int contractAccountVersion, final int offset) { final Bytes bytecode = code.getBytes(); // If the length of the program code is shorter than the required offset, halt execution. if (offset >= bytecode.size()) { return endOfScriptStop; } final byte opcode = bytecode.get(offset); final Operation operation = operations.get(opcode, contractAccountVersion); if (operation == null) { return new InvalidOperation(opcode, null); } else { return operation; } }
206414745_1849
@Override public void traceExecution(final MessageFrame frame, final ExecuteOperation executeOperation) { final Operation currentOperation = frame.getCurrentOperation(); final int depth = frame.getMessageStackDepth(); final String opcode = currentOperation.getName(); final int pc = frame.getPC(); final Gas gasRemaining = frame.getRemainingGas(); final Bytes inputData = frame.getInputData(); final Optional<Bytes32[]> stack = captureStack(frame); final WorldUpdater worldUpdater = frame.getWorldState(); final Optional<Bytes32[]> stackPostExecution; final OperationResult operationResult = executeOperation.execute(); final Bytes outputData = frame.getOutputData(); final Optional<Bytes[]> memory = captureMemory(frame); stackPostExecution = captureStack(frame); if (lastFrame != null) { lastFrame.setGasRemainingPostExecution(gasRemaining); } final Optional<Map<UInt256, UInt256>> storage = captureStorage(frame); final Optional<Map<Address, Wei>> maybeRefunds = frame.getRefunds().isEmpty() ? Optional.empty() : Optional.of(frame.getRefunds()); lastFrame = new TraceFrame( pc, Optional.of(opcode), gasRemaining, operationResult.getGasCost(), frame.getGasRefund(), depth, operationResult.getHaltReason(), frame.getRecipientAddress(), frame.getApparentValue(), inputData, outputData, stack, memory, storage, worldUpdater, frame.getRevertReason(), maybeRefunds, Optional.ofNullable(frame.getMessageFrameStack().peek()).map(MessageFrame::getCode), frame.getCurrentOperation().getStackItemsProduced(), stackPostExecution, currentOperation.isVirtualOperation(), frame.getMaybeUpdatedMemory(), frame.getMaybeUpdatedStorage()); traceFrames.add(lastFrame); frame.reset(); }
206414745_1850
public static List<Node<Bytes>> decodeNodes(final Bytes nodeRlp) { Node<Bytes> node = decode(nodeRlp); List<Node<Bytes>> nodes = new ArrayList<>(); nodes.add(node); final List<Node<Bytes>> toProcess = new ArrayList<>(); toProcess.addAll(node.getChildren()); while (!toProcess.isEmpty()) { final Node<Bytes> currentNode = toProcess.remove(0); if (Objects.equals(NullNode.instance(), currentNode)) { // Skip null nodes continue; } nodes.add(currentNode); if (!currentNode.isReferencedByHash()) { // If current node is inlined, that means we can process its children toProcess.addAll(currentNode.getChildren()); } } return nodes; }
206414745_1851
public static Stream<Node<Bytes>> breadthFirstDecoder( final NodeLoader nodeLoader, final Bytes32 rootHash, final int maxDepth) { checkArgument(maxDepth >= 0); return Streams.stream(new BreadthFirstIterator(nodeLoader, rootHash, maxDepth)); }
206414745_1852
public static Stream<Node<Bytes>> breadthFirstDecoder( final NodeLoader nodeLoader, final Bytes32 rootHash, final int maxDepth) { checkArgument(maxDepth >= 0); return Streams.stream(new BreadthFirstIterator(nodeLoader, rootHash, maxDepth)); }
206414745_1853
public static Stream<Node<Bytes>> breadthFirstDecoder( final NodeLoader nodeLoader, final Bytes32 rootHash, final int maxDepth) { checkArgument(maxDepth >= 0); return Streams.stream(new BreadthFirstIterator(nodeLoader, rootHash, maxDepth)); }
206414745_1854
public static Stream<Node<Bytes>> breadthFirstDecoder( final NodeLoader nodeLoader, final Bytes32 rootHash, final int maxDepth) { checkArgument(maxDepth >= 0); return Streams.stream(new BreadthFirstIterator(nodeLoader, rootHash, maxDepth)); }
206414745_1855
public static Stream<Node<Bytes>> breadthFirstDecoder( final NodeLoader nodeLoader, final Bytes32 rootHash, final int maxDepth) { checkArgument(maxDepth >= 0); return Streams.stream(new BreadthFirstIterator(nodeLoader, rootHash, maxDepth)); }
206414745_1856
public static Bytes bytesToPath(final Bytes bytes) { final MutableBytes path = MutableBytes.create(bytes.size() * 2 + 1); int j = 0; for (int i = 0; i < bytes.size(); i += 1, j += 2) { final byte b = bytes.get(i); path.set(j, (byte) ((b >>> 4) & 0x0f)); path.set(j + 1, (byte) (b & 0x0f)); } path.set(j, LEAF_TERMINATOR); return path; }
206414745_1857
public static Bytes encode(final Bytes path) { int size = path.size(); final boolean isLeaf = size > 0 && path.get(size - 1) == LEAF_TERMINATOR; if (isLeaf) { size = size - 1; } final MutableBytes encoded = MutableBytes.create((size + 2) / 2); int i = 0; int j = 0; if (size % 2 == 1) { // add first nibble to magic final byte high = (byte) (isLeaf ? 0x03 : 0x01); final byte low = path.get(i++); if ((low & 0xf0) != 0) { throw new IllegalArgumentException("Invalid path: contains elements larger than a nibble"); } encoded.set(j++, (byte) (high << 4 | low)); } else { final byte high = (byte) (isLeaf ? 0x02 : 0x00); encoded.set(j++, (byte) (high << 4)); } while (i < size) { final byte high = path.get(i++); final byte low = path.get(i++); if ((high & 0xf0) != 0 || (low & 0xf0) != 0) { throw new IllegalArgumentException("Invalid path: contains elements larger than a nibble"); } encoded.set(j++, (byte) (high << 4 | low)); } return encoded; }
206414745_1858
public static Bytes decode(final Bytes encoded) { final int size = encoded.size(); checkArgument(size > 0); final byte metadata = encoded.get(0); checkArgument((metadata & 0xc0) == 0, "Invalid compact encoding"); final boolean isLeaf = (metadata & 0x20) != 0; final int pathLength = ((size - 1) * 2) + (isLeaf ? 1 : 0); final MutableBytes path; int i = 0; if ((metadata & 0x10) != 0) { // need to use lower nibble of metadata path = MutableBytes.create(pathLength + 1); path.set(i++, (byte) (metadata & 0x0f)); } else { path = MutableBytes.create(pathLength); } for (int j = 1; j < size; j++) { final byte b = encoded.get(j); path.set(i++, (byte) ((b >>> 4) & 0x0f)); path.set(i++, (byte) (b & 0x0f)); } if (isLeaf) { path.set(i, LEAF_TERMINATOR); } return path; }
206414745_1859
@Override public void visit(final ExtensionNode<V> extensionNode) { handler.accept(extensionNode); acceptAndUnload(extensionNode.getChild()); }
206414745_1860
@Override public void visit(final ExtensionNode<V> extensionNode) { handler.accept(extensionNode); acceptAndUnload(extensionNode.getChild()); }
206414745_1861
@Override public Optional<EthHashBlockMiner> startAsyncMining( final Subscribers<MinedBlockObserver> observers, final Subscribers<EthHashObserver> ethHashObservers, final BlockHeader parentHeader) { if (coinbase.isEmpty()) { throw new CoinbaseNotSetException("Unable to start mining without a coinbase."); } return super.startAsyncMining(observers, ethHashObservers, parentHeader); }
206414745_1862
public void setCoinbase(final Address coinbase) { if (coinbase == null) { throw new IllegalArgumentException("Coinbase cannot be unset."); } else { this.coinbase = Optional.of(Address.wrap(coinbase.copy())); } }
206414745_1863
public Optional<Long> getHashesPerSecond() { return nonceSolver.hashesPerSecond(); }
206414745_1864
public TransactionSelectionResults buildTransactionListForBlock() { pendingTransactions.selectTransactions(this::evaluateTransaction); return transactionSelectionResult; }
206414745_1865
public TransactionSelectionResults buildTransactionListForBlock() { pendingTransactions.selectTransactions(this::evaluateTransaction); return transactionSelectionResult; }
206414745_1866
public TransactionSelectionResults buildTransactionListForBlock() { pendingTransactions.selectTransactions(this::evaluateTransaction); return transactionSelectionResult; }
206414745_1867
public TransactionSelectionResults buildTransactionListForBlock() { pendingTransactions.selectTransactions(this::evaluateTransaction); return transactionSelectionResult; }
206414745_1868
public TransactionSelectionResults buildTransactionListForBlock() { pendingTransactions.selectTransactions(this::evaluateTransaction); return transactionSelectionResult; }
206414745_1869
public TransactionSelectionResults buildTransactionListForBlock() { pendingTransactions.selectTransactions(this::evaluateTransaction); return transactionSelectionResult; }
206414745_1870
public TransactionSelectionResults buildTransactionListForBlock() { pendingTransactions.selectTransactions(this::evaluateTransaction); return transactionSelectionResult; }
206414745_1871
public TransactionSelectionResults buildTransactionListForBlock() { pendingTransactions.selectTransactions(this::evaluateTransaction); return transactionSelectionResult; }
206414745_1872
public TransactionSelectionResults buildTransactionListForBlock() { pendingTransactions.selectTransactions(this::evaluateTransaction); return transactionSelectionResult; }
206414745_1873
@Override @VisibleForTesting public BlockCreationTimeResult getNextTimestamp(final BlockHeader parentHeader) { final long msSinceEpoch = clock.millis(); final long now = TimeUnit.SECONDS.convert(msSinceEpoch, TimeUnit.MILLISECONDS); final long parentTimestamp = parentHeader.getTimestamp(); final long nextHeaderTimestamp = Long.max(parentTimestamp + minimumSecondsSinceParent, now); final long earliestBlockTransmissionTime = nextHeaderTimestamp - acceptableClockDriftSeconds; final long msUntilBlocKTransmission = (earliestBlockTransmissionTime * 1000) - msSinceEpoch; return new BlockCreationTimeResult(nextHeaderTimestamp, Math.max(0, msUntilBlocKTransmission)); }
206414745_1874
@Override @VisibleForTesting public BlockCreationTimeResult getNextTimestamp(final BlockHeader parentHeader) { final long msSinceEpoch = clock.millis(); final long now = TimeUnit.SECONDS.convert(msSinceEpoch, TimeUnit.MILLISECONDS); final long parentTimestamp = parentHeader.getTimestamp(); final long nextHeaderTimestamp = Long.max(parentTimestamp + minimumSecondsSinceParent, now); final long earliestBlockTransmissionTime = nextHeaderTimestamp - acceptableClockDriftSeconds; final long msUntilBlocKTransmission = (earliestBlockTransmissionTime * 1000) - msSinceEpoch; return new BlockCreationTimeResult(nextHeaderTimestamp, Math.max(0, msUntilBlocKTransmission)); }
206414745_1875
@Override @VisibleForTesting public BlockCreationTimeResult getNextTimestamp(final BlockHeader parentHeader) { final long msSinceEpoch = clock.millis(); final long now = TimeUnit.SECONDS.convert(msSinceEpoch, TimeUnit.MILLISECONDS); final long parentTimestamp = parentHeader.getTimestamp(); final long nextHeaderTimestamp = Long.max(parentTimestamp + minimumSecondsSinceParent, now); final long earliestBlockTransmissionTime = nextHeaderTimestamp - acceptableClockDriftSeconds; final long msUntilBlocKTransmission = (earliestBlockTransmissionTime * 1000) - msSinceEpoch; return new BlockCreationTimeResult(nextHeaderTimestamp, Math.max(0, msUntilBlocKTransmission)); }
206414745_1876
@Override @VisibleForTesting public BlockCreationTimeResult getNextTimestamp(final BlockHeader parentHeader) { final long msSinceEpoch = clock.millis(); final long now = TimeUnit.SECONDS.convert(msSinceEpoch, TimeUnit.MILLISECONDS); final long parentTimestamp = parentHeader.getTimestamp(); final long nextHeaderTimestamp = Long.max(parentTimestamp + minimumSecondsSinceParent, now); final long earliestBlockTransmissionTime = nextHeaderTimestamp - acceptableClockDriftSeconds; final long msUntilBlocKTransmission = (earliestBlockTransmissionTime * 1000) - msSinceEpoch; return new BlockCreationTimeResult(nextHeaderTimestamp, Math.max(0, msUntilBlocKTransmission)); }
206414745_1877
@Override public Iterator<Long> iterator() { return new Iterator<Long>() { @Override public boolean hasNext() { return true; } @Override public Long next() { return nextValue++; } }; }
206414745_1878
@Override public Iterator<Long> iterator() { return new Iterator<Long>() { @Override public boolean hasNext() { return true; } @Override public Long next() { return nextValue++; } }; }
206414745_1879
@Override public Optional<Long> hashesPerSecond() { if (sealerHashRate.size() <= 0) { return localHashesPerSecond(); } else { return remoteHashesPerSecond(); } }
207457953_1079
@Override public CompletableFuture<RegistrationResponse> registerJobManager( final JobMasterId jobMasterId, final ResourceID jobManagerResourceId, final String jobManagerAddress, final JobID jobId, final Time timeout) { checkNotNull(jobMasterId); checkNotNull(jobManagerResourceId); checkNotNull(jobManagerAddress); checkNotNull(jobId); if (!jobLeaderIdService.containsJob(jobId)) { try { jobLeaderIdService.addJob(jobId); } catch (Exception e) { ResourceManagerException exception = new ResourceManagerException("Could not add the job " + jobId + " to the job id leader service.", e); onFatalError(exception); log.error("Could not add job {} to job leader id service.", jobId, e); return FutureUtils.completedExceptionally(exception); } } log.info("Registering job manager {}@{} for job {}.", jobMasterId, jobManagerAddress, jobId); CompletableFuture<JobMasterId> jobMasterIdFuture; try { jobMasterIdFuture = jobLeaderIdService.getLeaderId(jobId); } catch (Exception e) { // we cannot check the job leader id so let's fail // TODO: Maybe it's also ok to skip this check in case that we cannot check the leader id ResourceManagerException exception = new ResourceManagerException("Cannot obtain the " + "job leader id future to verify the correct job leader.", e); onFatalError(exception); log.debug("Could not obtain the job leader id future to verify the correct job leader."); return FutureUtils.completedExceptionally(exception); } CompletableFuture<JobMasterGateway> jobMasterGatewayFuture = getRpcService().connect(jobManagerAddress, jobMasterId, JobMasterGateway.class); CompletableFuture<RegistrationResponse> registrationResponseFuture = jobMasterGatewayFuture.thenCombineAsync( jobMasterIdFuture, (JobMasterGateway jobMasterGateway, JobMasterId leadingJobMasterId) -> { if (Objects.equals(leadingJobMasterId, jobMasterId)) { return registerJobMasterInternal( jobMasterGateway, jobId, jobManagerAddress, jobManagerResourceId); } else { final String declineMessage = String.format( "The leading JobMaster id %s did not match the received JobMaster id %s. " + "This indicates that a JobMaster leader change has happened.", leadingJobMasterId, jobMasterId); log.debug(declineMessage); return new RegistrationResponse.Decline(declineMessage); } }, getMainThreadExecutor()); // handle exceptions which might have occurred in one of the futures inputs of combine return registrationResponseFuture.handleAsync( (RegistrationResponse registrationResponse, Throwable throwable) -> { if (throwable != null) { if (log.isDebugEnabled()) { log.debug("Registration of job manager {}@{} failed.", jobMasterId, jobManagerAddress, throwable); } else { log.info("Registration of job manager {}@{} failed.", jobMasterId, jobManagerAddress); } return new RegistrationResponse.Decline(throwable.getMessage()); } else { return registrationResponse; } }, getRpcService().getExecutor()); }
207457953_1080
@Override public CompletableFuture<RegistrationResponse> registerTaskExecutor( final String taskExecutorAddress, final ResourceID taskExecutorResourceId, final int dataPort, final HardwareDescription hardwareDescription, final Time timeout) { CompletableFuture<TaskExecutorGateway> taskExecutorGatewayFuture = getRpcService().connect(taskExecutorAddress, TaskExecutorGateway.class); taskExecutorGatewayFutures.put(taskExecutorResourceId, taskExecutorGatewayFuture); return taskExecutorGatewayFuture.handleAsync( (TaskExecutorGateway taskExecutorGateway, Throwable throwable) -> { if (taskExecutorGatewayFuture == taskExecutorGatewayFutures.get(taskExecutorResourceId)) { taskExecutorGatewayFutures.remove(taskExecutorResourceId); if (throwable != null) { return new RegistrationResponse.Decline(throwable.getMessage()); } else { return registerTaskExecutorInternal( taskExecutorGateway, taskExecutorAddress, taskExecutorResourceId, dataPort, hardwareDescription); } } else { log.info("Ignoring outdated TaskExecutorGateway connection."); return new RegistrationResponse.Decline("Decline outdated task executor registration."); } }, getMainThreadExecutor()); }
207457953_1126
@Override public CompletableFuture<Acknowledge> disconnectTaskManager(final ResourceID resourceID, final Exception cause) { log.debug("Disconnect TaskExecutor {} because: {}", resourceID, cause.getMessage()); taskManagerHeartbeatManager.unmonitorTarget(resourceID); slotPool.releaseTaskManager(resourceID, cause); Tuple2<TaskManagerLocation, TaskExecutorGateway> taskManagerConnection = registeredTaskManagers.remove(resourceID); if (taskManagerConnection != null) { taskManagerConnection.f1.disconnectJobManager(jobGraph.getJobID(), cause); } return CompletableFuture.completedFuture(Acknowledge.get()); }
207457953_1127
@Override public void heartbeatFromTaskManager(final ResourceID resourceID, AccumulatorReport accumulatorReport) { taskManagerHeartbeatManager.receiveHeartbeat(resourceID, accumulatorReport); }
207457953_1128
boolean offerSlot( final TaskManagerLocation taskManagerLocation, final TaskManagerGateway taskManagerGateway, final SlotOffer slotOffer) { componentMainThreadExecutor.assertRunningInMainThread(); // check if this TaskManager is valid final ResourceID resourceID = taskManagerLocation.getResourceID(); final AllocationID allocationID = slotOffer.getAllocationId(); if (!registeredTaskManagers.contains(resourceID)) { log.debug("Received outdated slot offering [{}] from unregistered TaskManager: {}", slotOffer.getAllocationId(), taskManagerLocation); return false; } // check whether we have already using this slot AllocatedSlot existingSlot; if ((existingSlot = allocatedSlots.get(allocationID)) != null || (existingSlot = availableSlots.get(allocationID)) != null) { // we need to figure out if this is a repeated offer for the exact same slot, // or another offer that comes from a different TaskManager after the ResourceManager // re-tried the request // we write this in terms of comparing slot IDs, because the Slot IDs are the identifiers of // the actual slots on the TaskManagers // Note: The slotOffer should have the SlotID final SlotID existingSlotId = existingSlot.getSlotId(); final SlotID newSlotId = new SlotID(taskManagerLocation.getResourceID(), slotOffer.getSlotIndex()); if (existingSlotId.equals(newSlotId)) { log.info("Received repeated offer for slot [{}]. Ignoring.", allocationID); // return true here so that the sender will get a positive acknowledgement to the retry // and mark the offering as a success return true; } else { // the allocation has been fulfilled by another slot, reject the offer so the task executor // will offer the slot to the resource manager return false; } } final AllocatedSlot allocatedSlot = new AllocatedSlot( allocationID, taskManagerLocation, slotOffer.getSlotIndex(), slotOffer.getResourceProfile(), taskManagerGateway); // check whether we have request waiting for this slot PendingRequest pendingRequest = pendingRequests.removeKeyB(allocationID); if (pendingRequest != null) { // we were waiting for this! allocatedSlots.add(pendingRequest.getSlotRequestId(), allocatedSlot); if (!pendingRequest.getAllocatedSlotFuture().complete(allocatedSlot)) { // we could not complete the pending slot future --> try to fulfill another pending request allocatedSlots.remove(pendingRequest.getSlotRequestId()); tryFulfillSlotRequestOrMakeAvailable(allocatedSlot); } else { log.debug("Fulfilled slot request [{}] with allocated slot [{}].", pendingRequest.getSlotRequestId(), allocationID); } } else { // we were actually not waiting for this: // - could be that this request had been fulfilled // - we are receiving the slots from TaskManagers after becoming leaders tryFulfillSlotRequestOrMakeAvailable(allocatedSlot); } // we accepted the request in any case. slot will be released after it idled for // too long and timed out return true; }
207457953_1129
private void checkIdleSlot() { // The timestamp in SlotAndTimestamp is relative final long currentRelativeTimeMillis = clock.relativeTimeMillis(); final List<AllocatedSlot> expiredSlots = new ArrayList<>(availableSlots.size()); for (SlotAndTimestamp slotAndTimestamp : availableSlots.availableSlots.values()) { if (currentRelativeTimeMillis - slotAndTimestamp.timestamp > idleSlotTimeout.toMilliseconds()) { expiredSlots.add(slotAndTimestamp.slot); } } final FlinkException cause = new FlinkException("Releasing idle slot."); for (AllocatedSlot expiredSlot : expiredSlots) { final AllocationID allocationID = expiredSlot.getAllocationId(); if (availableSlots.tryRemove(allocationID) != null) { log.info("Releasing idle slot [{}].", allocationID); final CompletableFuture<Acknowledge> freeSlotFuture = expiredSlot.getTaskManagerGateway().freeSlot( allocationID, cause, rpcTimeout); FutureUtils.whenCompleteAsyncIfNotDone( freeSlotFuture, componentMainThreadExecutor, (Acknowledge ignored, Throwable throwable) -> { if (throwable != null) { // The slot status will be synced to task manager in next heartbeat. log.debug("Releasing slot [{}] of registered TaskExecutor {} failed. Discarding slot.", allocationID, expiredSlot.getTaskManagerId(), throwable); } }); } } scheduleRunAsync(this::checkIdleSlot, idleSlotTimeout); }
207457953_1130
@Override public Optional<ResourceID> failAllocation(final AllocationID allocationID, final Exception cause) { componentMainThreadExecutor.assertRunningInMainThread(); final PendingRequest pendingRequest = pendingRequests.removeKeyB(allocationID); if (pendingRequest != null) { // request was still pending failPendingRequest(pendingRequest, cause); return Optional.empty(); } else { return tryFailingAllocatedSlot(allocationID, cause); } // TODO: add some unit tests when the previous two are ready, the allocation may failed at any phase }
207457953_1131
@Override public AllocatedSlotReport createAllocatedSlotReport(ResourceID taskManagerId) { final Set<AllocatedSlot> availableSlotsForTaskManager = availableSlots.getSlotsForTaskManager(taskManagerId); final Set<AllocatedSlot> allocatedSlotsForTaskManager = allocatedSlots.getSlotsForTaskManager(taskManagerId); List<AllocatedSlotInfo> allocatedSlotInfos = new ArrayList<>( availableSlotsForTaskManager.size() + allocatedSlotsForTaskManager.size()); for (AllocatedSlot allocatedSlot : Iterables.concat(availableSlotsForTaskManager, allocatedSlotsForTaskManager)) { allocatedSlotInfos.add( new AllocatedSlotInfo(allocatedSlot.getPhysicalSlotNumber(), allocatedSlot.getAllocationId())); } return new AllocatedSlotReport(jobId, allocatedSlotInfos); }
207457953_1189
public SharedBuffer(KeyedStateStore stateStore, TypeSerializer<V> valueSerializer) { this.eventsBuffer = stateStore.getMapState( new MapStateDescriptor<>( eventsStateName, EventId.EventIdSerializer.INSTANCE, new Lockable.LockableTypeSerializer<>(valueSerializer))); this.entries = stateStore.getMapState( new MapStateDescriptor<>( entriesStateName, new NodeId.NodeIdSerializer(), new Lockable.LockableTypeSerializer<>(new SharedBufferNode.SharedBufferNodeSerializer()))); this.eventsCount = stateStore.getMapState( new MapStateDescriptor<>( eventsCountStateName, LongSerializer.INSTANCE, IntSerializer.INSTANCE)); }
223551095_1003
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{ clusterName=").append(clusterName) .append(", clusterId=").append(clusterId) .append(", provisioningState=").append(provisioningState) .append(", desiredStackVersion=").append(desiredStackVersion) .append(", totalHosts=").append(totalHosts) .append(", hosts=["); if (hostNames != null) { int i = 0; for (String hostName : hostNames) { if (i != 0) { sb.append(","); } ++i; sb.append(hostName); } } sb.append("], clusterHealthReport= ").append(clusterHealthReport).append("}"); return sb.toString(); }
223551095_1006
public Long getId() { return id; }
223551095_1007
public long getLastStageId() { return stages.isEmpty() ? -1 : stages.get(stages.size() - 1).getStageId(); }
223551095_1008
public State getProjectedState(String host, String component) { RoleCommand lastCommand = null; ListIterator<Stage> iterator = stages.listIterator(stages.size()); while (lastCommand == null && iterator.hasPrevious()) { Stage stage = iterator.previous(); Map<String, Map<String, HostRoleCommand>> stageCommands = stage.getHostRoleCommands(); if (stageCommands != null) { Map<String, HostRoleCommand> hostCommands = stageCommands.get(host); if (hostCommands != null) { HostRoleCommand roleCommand = hostCommands.get(component); if (roleCommand != null && roleCommand.getRoleCommand() != RoleCommand.SERVICE_CHECK) { lastCommand = roleCommand.getRoleCommand(); } } } } State resultingState = null; if (lastCommand != null) { switch(lastCommand) { case INSTALL: case STOP: resultingState = State.INSTALLED; break; case START: resultingState = State.STARTED; break; case UNINSTALL: resultingState = State.INIT; break; default: resultingState = State.UNKNOWN; } } return resultingState; }
223551095_1009
public void persist() throws AmbariException { if (!stages.isEmpty()) { Request request = (null == actionRequest) ? requestFactory.createNewFromStages(stages, clusterHostInfo) : requestFactory.createNewFromStages(stages, clusterHostInfo, actionRequest); if (null != requestContext) { request.setRequestContext(requestContext); } if (request != null) { //request can be null at least in JUnit request.setUserName(AuthorizationHelper.getAuthenticatedName()); } if (request != null && request.getStages()!= null && !request.getStages().isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("Triggering Action Manager, request={}", request); } actionManager.sendActions(request, actionRequest); } } }
223551095_1010
public void persist() throws AmbariException { if (!stages.isEmpty()) { Request request = (null == actionRequest) ? requestFactory.createNewFromStages(stages, clusterHostInfo) : requestFactory.createNewFromStages(stages, clusterHostInfo, actionRequest); if (null != requestContext) { request.setRequestContext(requestContext); } if (request != null) { //request can be null at least in JUnit request.setUserName(AuthorizationHelper.getAuthenticatedName()); } if (request != null && request.getStages()!= null && !request.getStages().isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("Triggering Action Manager, request={}", request); } actionManager.sendActions(request, actionRequest); } } }
223551095_1011
public RequestStatusResponse getRequestStatusResponse() { RequestStatusResponse response = null; if (! stages.isEmpty()) { response = new RequestStatusResponse(id); List<HostRoleCommand> hostRoleCommands = actionManager.getRequestTasks(id); response.setRequestContext(actionManager.getRequestContext(id)); List<ShortTaskStatus> tasks = new ArrayList<>(); for (HostRoleCommand hostRoleCommand : hostRoleCommands) { tasks.add(new ShortTaskStatus(hostRoleCommand)); } response.setTasks(tasks); } return response; }
223551095_1012
@Override protected PermissionEntity getPermission(String permissionName, ResourceEntity resourceEntity) throws AmbariException { return (permissionName.equals(PermissionEntity.VIEW_USER_PERMISSION_NAME)) ? viewUsePermission : super.getPermission(permissionName, resourceEntity); }
223551095_1013
public Set<String> getPropertyIds() { return propertyIds; }
223551095_1014
public Set<String> checkPropertyIds(Set<String> propertyIds) { if (!this.propertyIds.containsAll(propertyIds)) { Set<String> unsupportedPropertyIds = new HashSet<>(propertyIds); unsupportedPropertyIds.removeAll(combinedIds); // If the property id is not in the set of known property ids we may still allow it if // its parent category is a known property. This allows for Map type properties where // we want to treat property as a category and the entries as individual properties. Set<String> categoryProperties = new HashSet<>(); for (String unsupportedPropertyId : unsupportedPropertyIds) { if (checkCategory(unsupportedPropertyId) || checkRegExp(unsupportedPropertyId)) { categoryProperties.add(unsupportedPropertyId); } } unsupportedPropertyIds.removeAll(categoryProperties); return unsupportedPropertyIds; } return Collections.emptySet(); }
223551095_1015
protected Set<String> getRequestPropertyIds(Request request, Predicate predicate) { Set<String> propertyIds = request.getPropertyIds(); // if no properties are specified, then return them all if (propertyIds == null || propertyIds.isEmpty()) { return new HashSet<>(this.propertyIds); } propertyIds = new HashSet<>(propertyIds); if (predicate != null) { propertyIds.addAll(PredicateHelper.getPropertyIds(predicate)); } if (!combinedIds.containsAll(propertyIds)) { Set<String> keepers = new HashSet<>(); Set<String> unsupportedPropertyIds = new HashSet<>(propertyIds); unsupportedPropertyIds.removeAll(combinedIds); for (String unsupportedPropertyId : unsupportedPropertyIds) { if (checkCategory(unsupportedPropertyId) || checkRegExp(unsupportedPropertyId)) { keepers.add(unsupportedPropertyId); } } propertyIds.retainAll(combinedIds); propertyIds.addAll(keepers); } return propertyIds; }
223551095_1016
protected static boolean setResourceProperty(Resource resource, String propertyId, Object value, Set<String> requestedIds) { boolean contains = requestedIds.contains(propertyId) || isPropertyCategoryRequested(propertyId, requestedIds); if (contains) { if (LOG.isDebugEnabled()) { LOG.debug("Setting property for resource, resourceType={}, propertyId={}, value={}", resource.getType(), propertyId, value); } // If the value is a Map then set all of its entries as properties if (!setResourceMapProperty(resource, propertyId, value)){ resource.setProperty(propertyId, value); } } else { if (value instanceof Map<?, ?>) { // This map wasn't requested, but maybe some of its entries were... Map<?, ?> mapValue = (Map) value; for (Map.Entry entry : mapValue.entrySet()) { String entryPropertyId = PropertyHelper.getPropertyId(propertyId, entry.getKey().toString()); Object entryValue = entry.getValue(); contains = setResourceProperty(resource, entryPropertyId, entryValue, requestedIds) || contains; } } if (!contains && LOG.isDebugEnabled()) { LOG.debug("Skipping property for resource as not in requestedIds, resourceType={}, propertyId={}, value={}", resource.getType(), propertyId, value); } } return contains; }
223551095_1017
protected static boolean isPropertyRequested(String propertyId, Set<String> requestedIds) { return requestedIds.contains(propertyId) || isPropertyCategoryRequested(propertyId, requestedIds) || isPropertyEntryRequested(propertyId, requestedIds); }
223551095_1018
protected static boolean setResourceProperty(Resource resource, String propertyId, Object value, Set<String> requestedIds) { boolean contains = requestedIds.contains(propertyId) || isPropertyCategoryRequested(propertyId, requestedIds); if (contains) { if (LOG.isDebugEnabled()) { LOG.debug("Setting property for resource, resourceType={}, propertyId={}, value={}", resource.getType(), propertyId, value); } // If the value is a Map then set all of its entries as properties if (!setResourceMapProperty(resource, propertyId, value)){ resource.setProperty(propertyId, value); } } else { if (value instanceof Map<?, ?>) { // This map wasn't requested, but maybe some of its entries were... Map<?, ?> mapValue = (Map) value; for (Map.Entry entry : mapValue.entrySet()) { String entryPropertyId = PropertyHelper.getPropertyId(propertyId, entry.getKey().toString()); Object entryValue = entry.getValue(); contains = setResourceProperty(resource, entryPropertyId, entryValue, requestedIds) || contains; } } if (!contains && LOG.isDebugEnabled()) { LOG.debug("Skipping property for resource as not in requestedIds, resourceType={}, propertyId={}, value={}", resource.getType(), propertyId, value); } } return contains; }
223551095_1019
protected Map.Entry<String, Pattern> getRegexEntry(String id) { Map.Entry<String, Pattern> regexEntry = null; for (Map.Entry<String, Pattern> entry : patterns.entrySet()) { Pattern pattern = entry.getValue(); Matcher matcher = pattern.matcher(id); if (matcher.matches()) { String key = entry.getKey(); if (regexEntry == null || key.startsWith(regexEntry.getKey())) { regexEntry = entry; } } } return regexEntry; }
223551095_1020
@Override public Set<Resource> getResources() { return resources; }
223551095_1021
@Override public boolean isSortedResponse() { return sortedResponse; }
223551095_1022
@Override public boolean isPagedResponse() { return pagedResponse; }
223551095_1023
@Override public int getTotalResourceCount() { return totalResourceCount; }
223551095_1025
@Override public void addCategory(String id) { String categoryKey = getCategoryKey(id); if (!propertiesMap.containsKey(categoryKey)) { propertiesMap.put(categoryKey, new HashMap<>()); } }
223551095_1028
public String getQuickLinksProfileJson() { return quickLinksProfileJson; }
223551095_1029
public String getQuickLinksProfileJson() { return quickLinksProfileJson; }
223551095_1030
public String getQuickLinksProfileJson() { return quickLinksProfileJson; }
223551095_1031
public String getQuickLinksProfileJson() { return quickLinksProfileJson; }
223551095_1032
@Override public RequestStatus createResources(Request request) throws SystemException, UnsupportedPropertyException, ResourceAlreadyExistsException, NoSuchParentResourceException { // we can't create instances directly throw new UnsupportedOperationException("Not supported."); }
223551095_1033
@Override public Set<Resource> getResources(Request request, Predicate predicate) throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException { Set<String> requestedIds = getRequestPropertyIds(request, predicate); Set<Resource> resources = new HashSet<>(); List<String> feedNames = new LinkedList<>(); IvoryService service = getService(); if (predicate == null) { feedNames = service.getFeedNames(); } else { for (Map<String, Object> propertyMap : getPropertyMaps(predicate)) { String feedName = (String) propertyMap.get(INSTANCE_FEED_NAME_PROPERTY_ID); if (feedName == null) { // if any part of the predicate doesn't include feed name then we have to check them all feedNames = service.getFeedNames(); break; } feedNames.add(feedName); } } for (String feedName : feedNames) { List<Instance> instances = service.getInstances(feedName); for (Instance instance : instances) { Resource resource = new ResourceImpl(Resource.Type.DRInstance); setResourceProperty(resource, INSTANCE_FEED_NAME_PROPERTY_ID, instance.getFeedName(), requestedIds); setResourceProperty(resource, INSTANCE_ID_PROPERTY_ID, instance.getId(), requestedIds); setResourceProperty(resource, INSTANCE_STATUS_PROPERTY_ID, instance.getStatus(), requestedIds); setResourceProperty(resource, INSTANCE_START_TIME_PROPERTY_ID, instance.getStartTime(), requestedIds); setResourceProperty(resource, INSTANCE_END_TIME_PROPERTY_ID, instance.getEndTime(), requestedIds); setResourceProperty(resource, INSTANCE_DETAILS_PROPERTY_ID, instance.getDetails(), requestedIds); setResourceProperty(resource, INSTANCE_LOG_PROPERTY_ID, instance.getLog(), requestedIds); if (predicate == null || predicate.evaluate(resource)) { resources.add(resource); } } } return resources; }
223551095_1034
@Override public RequestStatus updateResources(Request request, Predicate predicate) throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException { IvoryService service = getService(); Iterator<Map<String,Object>> iterator = request.getProperties().iterator(); if (iterator.hasNext()) { Map<String, Object> propertyMap = iterator.next(); String desiredStatus = (String) propertyMap.get(INSTANCE_STATUS_PROPERTY_ID); if (desiredStatus != null) { // get all the instances that pass the predicate check Set<Resource> resources = getResources(PropertyHelper.getReadRequest(), predicate); // update all the matching instances with the property values from the request for (Resource resource : resources) { String status = (String) resource.getPropertyValue(INSTANCE_STATUS_PROPERTY_ID); String feedName = (String) resource.getPropertyValue(INSTANCE_FEED_NAME_PROPERTY_ID); String id = (String) resource.getPropertyValue(INSTANCE_ID_PROPERTY_ID); if (desiredStatus.equals("SUSPENDED")) { service.suspendInstance(feedName, id); } else if (status.equals("SUSPENDED") && desiredStatus.equals("RUNNING")) { service.resumeInstance(feedName, id); } } } } return new RequestStatusImpl(null); }
223551095_1035
@Override public RequestStatus deleteResources(Request request, Predicate predicate) throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException { IvoryService service = getService(); // get all the instances that pass the predicate check Set<Resource> resources = getResources(PropertyHelper.getReadRequest(), predicate); for (Resource resource : resources) { // delete all the matching instances with the property values from the request service.killInstance((String) resource.getPropertyValue(INSTANCE_FEED_NAME_PROPERTY_ID), (String) resource.getPropertyValue(INSTANCE_ID_PROPERTY_ID)); } return new RequestStatusImpl(null); }
223551095_1036
protected Map<String, Map<String, Map<String, String>>> calculateConfigurations(Request request) { Map<String, Map<String, Map<String, String>>> configurations = new HashMap<>(); Map<String, Object> properties = request.getProperties().iterator().next(); for (String property : properties.keySet()) { if (property.startsWith(CONFIGURATIONS_PROPERTY_ID)) { try { String propertyEnd = property.substring(CONFIGURATIONS_PROPERTY_ID.length()); // mapred-site/properties/yarn.app.mapreduce.am.resource.mb String[] propertyPath = propertyEnd.split("/"); // length == 3 String siteName = propertyPath[0]; String propertiesProperty = propertyPath[1]; String propertyName = propertyPath[2]; Map<String, Map<String, String>> siteMap = configurations.get(siteName); if (siteMap == null) { siteMap = new HashMap<>(); configurations.put(siteName, siteMap); } Map<String, String> propertiesMap = siteMap.get(propertiesProperty); if (propertiesMap == null) { propertiesMap = new HashMap<>(); siteMap.put(propertiesProperty, propertiesMap); } Object propVal = properties.get(property); if (propVal != null) propertiesMap.put(propertyName, propVal.toString()); else LOG.info(String.format("No value specified for configuration property, name = %s ", property)); } catch (Exception e) { LOG.debug(String.format("Error handling configuration property, name = %s", property), e); // do nothing } } } return configurations; }
223551095_1037
protected Map<String, String> readUserContext(Request request) { HashMap<String, String> userContext = new HashMap<>(); if (null != getRequestProperty(request, USER_CONTEXT_OPERATION_PROPERTY)) { userContext.put(OPERATION_PROPERTY, (String) getRequestProperty(request, USER_CONTEXT_OPERATION_PROPERTY)); } if (null != getRequestProperty(request, USER_CONTEXT_OPERATION_DETAILS_PROPERTY)) { userContext.put(OPERATION_DETAILS_PROPERTY, (String) getRequestProperty(request, USER_CONTEXT_OPERATION_DETAILS_PROPERTY)); } return userContext; }
223551095_1038
protected Map<String, Map<String, Map<String, String>>> calculateConfigurations(Request request) { Map<String, Map<String, Map<String, String>>> configurations = new HashMap<>(); Map<String, Object> properties = request.getProperties().iterator().next(); for (String property : properties.keySet()) { if (property.startsWith(CONFIGURATIONS_PROPERTY_ID)) { try { String propertyEnd = property.substring(CONFIGURATIONS_PROPERTY_ID.length()); // mapred-site/properties/yarn.app.mapreduce.am.resource.mb String[] propertyPath = propertyEnd.split("/"); // length == 3 String siteName = propertyPath[0]; String propertiesProperty = propertyPath[1]; String propertyName = propertyPath[2]; Map<String, Map<String, String>> siteMap = configurations.get(siteName); if (siteMap == null) { siteMap = new HashMap<>(); configurations.put(siteName, siteMap); } Map<String, String> propertiesMap = siteMap.get(propertiesProperty); if (propertiesMap == null) { propertiesMap = new HashMap<>(); siteMap.put(propertiesProperty, propertiesMap); } Object propVal = properties.get(property); if (propVal != null) propertiesMap.put(propertyName, propVal.toString()); else LOG.info(String.format("No value specified for configuration property, name = %s ", property)); } catch (Exception e) { LOG.debug(String.format("Error handling configuration property, name = %s", property), e); // do nothing } } } return configurations; }
223551095_1039
public static String getInternalLevelName(String external) throws IllegalArgumentException{ String refinedAlias = external.trim().toUpperCase(); for (String [] pair : LEVEL_ALIASES) { if (pair[ALIAS_COLUMN].equals(refinedAlias)) { return pair[INTERNAL_NAME_COLUMN]; } } String message = String.format("Unknown operation level %s", external); throw new IllegalArgumentException(message); }
223551095_1040
public static String getExternalLevelName(String internal) { for (String [] pair : LEVEL_ALIASES) { if (pair[INTERNAL_NAME_COLUMN].equals(internal)) { return pair[ALIAS_COLUMN]; } } // That should never happen String message = String.format("Unknown internal " + "operation level name %s", internal); throw new IllegalArgumentException(message); }
223551095_1041
protected Set<ServiceComponentResponse> getComponents(Set<ServiceComponentRequest> requests) throws AmbariException { Set<ServiceComponentResponse> response = new HashSet<>(); for (ServiceComponentRequest request : requests) { try { response.addAll(getComponents(request)); } catch (ObjectNotFoundException e) { if (requests.size() == 1) { // only throw exception if 1 request. // there will be > 1 request in case of OR predicate throw e; } } } return response; }
223551095_1042
@Override public Set<Resource> getResources(Request request, Predicate predicate) throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException { final Set<Resource> resources = new HashSet<>(); final Set<String> requestedIds = getRequestPropertyIds(request, predicate); final Set<Map<String, Object>> propertyMaps = getPropertyMaps(predicate); for (Map<String, Object> propertyMap: propertyMaps) { final String hostName = propertyMap.get(HOST_STACK_VERSION_HOST_NAME_PROPERTY_ID).toString(); String clusterName = null; if (propertyMap.containsKey(HOST_STACK_VERSION_CLUSTER_NAME_PROPERTY_ID)) { clusterName = propertyMap.get(HOST_STACK_VERSION_CLUSTER_NAME_PROPERTY_ID).toString(); } final Long id; List<HostVersionEntity> requestedEntities; if (propertyMap.get(HOST_STACK_VERSION_ID_PROPERTY_ID) == null) { if (clusterName == null) { requestedEntities = hostVersionDAO.findByHost(hostName); } else { requestedEntities = hostVersionDAO.findByClusterAndHost(clusterName, hostName); } } else { try { id = Long.parseLong(propertyMap.get(HOST_STACK_VERSION_ID_PROPERTY_ID).toString()); } catch (Exception ex) { throw new SystemException("Stack version should have numerical id"); } final HostVersionEntity entity = hostVersionDAO.findByPK(id); if (entity == null) { throw new NoSuchResourceException("There is no stack version with id " + id); } else { requestedEntities = Collections.singletonList(entity); } } if (requestedEntities != null) { addRequestedEntities(resources, requestedEntities, requestedIds, clusterName); } } return resources; }
223551095_1043
@Override public RequestStatus createResources(Request request) throws SystemException, UnsupportedPropertyException, ResourceAlreadyExistsException, NoSuchParentResourceException { Iterator<Map<String,Object>> iterator = request.getProperties().iterator(); String hostName; final String desiredRepoVersion; String stackName; String stackVersion; if (request.getProperties().size() > 1) { throw new UnsupportedOperationException("Multiple requests cannot be executed at the same time."); } Map<String, Object> propertyMap = iterator.next(); Set<String> requiredProperties = Sets.newHashSet( HOST_STACK_VERSION_HOST_NAME_PROPERTY_ID, HOST_STACK_VERSION_REPO_VERSION_PROPERTY_ID, HOST_STACK_VERSION_STACK_PROPERTY_ID, HOST_STACK_VERSION_VERSION_PROPERTY_ID); for (String requiredProperty : requiredProperties) { Validate.isTrue(propertyMap.containsKey(requiredProperty), String.format("The required property %s is not defined", requiredProperty)); } String clName = (String) propertyMap.get (HOST_STACK_VERSION_CLUSTER_NAME_PROPERTY_ID); hostName = (String) propertyMap.get(HOST_STACK_VERSION_HOST_NAME_PROPERTY_ID); desiredRepoVersion = (String) propertyMap.get(HOST_STACK_VERSION_REPO_VERSION_PROPERTY_ID); stackName = (String) propertyMap.get(HOST_STACK_VERSION_STACK_PROPERTY_ID); stackVersion = (String) propertyMap.get(HOST_STACK_VERSION_VERSION_PROPERTY_ID); boolean forceInstallOnNonMemberHost = false; Set<Map<String, String>> componentNames = null; String forceInstallOnNonMemberHostString = (String) propertyMap.get (HOST_STACK_VERSION_FORCE_INSTALL_ON_NON_MEMBER_HOST_PROPERTY_ID); if (BooleanUtils.toBoolean(forceInstallOnNonMemberHostString)) { forceInstallOnNonMemberHost = true; componentNames = (Set<Map<String, String>>) propertyMap.get(HOST_STACK_VERSION_COMPONENT_NAMES_PROPERTY_ID); if (componentNames == null) { throw new IllegalArgumentException("In case " + HOST_STACK_VERSION_FORCE_INSTALL_ON_NON_MEMBER_HOST_PROPERTY_ID + " is set to true, the list of " + "components should be specified in request."); } } RequestStageContainer req = createInstallPackagesRequest(hostName, desiredRepoVersion, stackName, stackVersion, clName, forceInstallOnNonMemberHost, componentNames); return getRequestStatus(req.getRequestStatusResponse()); }
223551095_1044
@Override public RequestStatus createResources(Request request) throws SystemException, UnsupportedPropertyException, ResourceAlreadyExistsException, NoSuchParentResourceException { Iterator<Map<String,Object>> iterator = request.getProperties().iterator(); String hostName; final String desiredRepoVersion; String stackName; String stackVersion; if (request.getProperties().size() > 1) { throw new UnsupportedOperationException("Multiple requests cannot be executed at the same time."); } Map<String, Object> propertyMap = iterator.next(); Set<String> requiredProperties = Sets.newHashSet( HOST_STACK_VERSION_HOST_NAME_PROPERTY_ID, HOST_STACK_VERSION_REPO_VERSION_PROPERTY_ID, HOST_STACK_VERSION_STACK_PROPERTY_ID, HOST_STACK_VERSION_VERSION_PROPERTY_ID); for (String requiredProperty : requiredProperties) { Validate.isTrue(propertyMap.containsKey(requiredProperty), String.format("The required property %s is not defined", requiredProperty)); } String clName = (String) propertyMap.get (HOST_STACK_VERSION_CLUSTER_NAME_PROPERTY_ID); hostName = (String) propertyMap.get(HOST_STACK_VERSION_HOST_NAME_PROPERTY_ID); desiredRepoVersion = (String) propertyMap.get(HOST_STACK_VERSION_REPO_VERSION_PROPERTY_ID); stackName = (String) propertyMap.get(HOST_STACK_VERSION_STACK_PROPERTY_ID); stackVersion = (String) propertyMap.get(HOST_STACK_VERSION_VERSION_PROPERTY_ID); boolean forceInstallOnNonMemberHost = false; Set<Map<String, String>> componentNames = null; String forceInstallOnNonMemberHostString = (String) propertyMap.get (HOST_STACK_VERSION_FORCE_INSTALL_ON_NON_MEMBER_HOST_PROPERTY_ID); if (BooleanUtils.toBoolean(forceInstallOnNonMemberHostString)) { forceInstallOnNonMemberHost = true; componentNames = (Set<Map<String, String>>) propertyMap.get(HOST_STACK_VERSION_COMPONENT_NAMES_PROPERTY_ID); if (componentNames == null) { throw new IllegalArgumentException("In case " + HOST_STACK_VERSION_FORCE_INSTALL_ON_NON_MEMBER_HOST_PROPERTY_ID + " is set to true, the list of " + "components should be specified in request."); } } RequestStageContainer req = createInstallPackagesRequest(hostName, desiredRepoVersion, stackName, stackVersion, clName, forceInstallOnNonMemberHost, componentNames); return getRequestStatus(req.getRequestStatusResponse()); }
223551095_1045
@Override public RequestStatus createResources(Request request) throws SystemException, UnsupportedPropertyException, ResourceAlreadyExistsException, NoSuchParentResourceException { Iterator<Map<String,Object>> iterator = request.getProperties().iterator(); String hostName; final String desiredRepoVersion; String stackName; String stackVersion; if (request.getProperties().size() > 1) { throw new UnsupportedOperationException("Multiple requests cannot be executed at the same time."); } Map<String, Object> propertyMap = iterator.next(); Set<String> requiredProperties = Sets.newHashSet( HOST_STACK_VERSION_HOST_NAME_PROPERTY_ID, HOST_STACK_VERSION_REPO_VERSION_PROPERTY_ID, HOST_STACK_VERSION_STACK_PROPERTY_ID, HOST_STACK_VERSION_VERSION_PROPERTY_ID); for (String requiredProperty : requiredProperties) { Validate.isTrue(propertyMap.containsKey(requiredProperty), String.format("The required property %s is not defined", requiredProperty)); } String clName = (String) propertyMap.get (HOST_STACK_VERSION_CLUSTER_NAME_PROPERTY_ID); hostName = (String) propertyMap.get(HOST_STACK_VERSION_HOST_NAME_PROPERTY_ID); desiredRepoVersion = (String) propertyMap.get(HOST_STACK_VERSION_REPO_VERSION_PROPERTY_ID); stackName = (String) propertyMap.get(HOST_STACK_VERSION_STACK_PROPERTY_ID); stackVersion = (String) propertyMap.get(HOST_STACK_VERSION_VERSION_PROPERTY_ID); boolean forceInstallOnNonMemberHost = false; Set<Map<String, String>> componentNames = null; String forceInstallOnNonMemberHostString = (String) propertyMap.get (HOST_STACK_VERSION_FORCE_INSTALL_ON_NON_MEMBER_HOST_PROPERTY_ID); if (BooleanUtils.toBoolean(forceInstallOnNonMemberHostString)) { forceInstallOnNonMemberHost = true; componentNames = (Set<Map<String, String>>) propertyMap.get(HOST_STACK_VERSION_COMPONENT_NAMES_PROPERTY_ID); if (componentNames == null) { throw new IllegalArgumentException("In case " + HOST_STACK_VERSION_FORCE_INSTALL_ON_NON_MEMBER_HOST_PROPERTY_ID + " is set to true, the list of " + "components should be specified in request."); } } RequestStageContainer req = createInstallPackagesRequest(hostName, desiredRepoVersion, stackName, stackVersion, clName, forceInstallOnNonMemberHost, componentNames); return getRequestStatus(req.getRequestStatusResponse()); }
223551095_1046
@Override public Set<Resource> populateResources(Set<Resource> resources, Request request, Predicate predicate) throws SystemException { Set<String> ids = getRequestPropertyIds(request, predicate); if (ids.size() == 0) { return resources; } for (Resource resource : resources) { String clusterName = (String) resource.getPropertyValue(clusterNamePropertyId); String hostName = (String) resource.getPropertyValue(hostNamePropertyId); String publicHostName = (String) resource.getPropertyValue(publicHostNamePropertyId); String componentName = (String) resource.getPropertyValue(componentNamePropertyId); if (clusterName != null && hostName != null && componentName != null && httpPropertyRequests.containsKey(componentName)) { try { Cluster cluster = clusters.getCluster(clusterName); List<HttpPropertyRequest> httpPropertyRequestList = httpPropertyRequests.get(componentName); for (HttpPropertyRequest httpPropertyRequest : httpPropertyRequestList) { populateResource(httpPropertyRequest, resource, cluster, hostName, publicHostName); } } catch (AmbariException e) { String msg = String.format("Could not load cluster with name %s.", clusterName); LOG.debug(msg, e); throw new SystemException(msg, e); } } } return resources; }
223551095_1047
@Override public Set<Resource> populateResources(Set<Resource> resources, Request request, Predicate predicate) throws SystemException { Set<String> ids = getRequestPropertyIds(request, predicate); if (ids.size() == 0) { return resources; } for (Resource resource : resources) { String clusterName = (String) resource.getPropertyValue(clusterNamePropertyId); String hostName = (String) resource.getPropertyValue(hostNamePropertyId); String publicHostName = (String) resource.getPropertyValue(publicHostNamePropertyId); String componentName = (String) resource.getPropertyValue(componentNamePropertyId); if (clusterName != null && hostName != null && componentName != null && httpPropertyRequests.containsKey(componentName)) { try { Cluster cluster = clusters.getCluster(clusterName); List<HttpPropertyRequest> httpPropertyRequestList = httpPropertyRequests.get(componentName); for (HttpPropertyRequest httpPropertyRequest : httpPropertyRequestList) { populateResource(httpPropertyRequest, resource, cluster, hostName, publicHostName); } } catch (AmbariException e) { String msg = String.format("Could not load cluster with name %s.", clusterName); LOG.debug(msg, e); throw new SystemException(msg, e); } } } return resources; }
223551095_1048
@Override public Set<Resource> populateResources(Set<Resource> resources, Request request, Predicate predicate) throws SystemException { Set<String> ids = getRequestPropertyIds(request, predicate); if (ids.size() == 0) { return resources; } for (Resource resource : resources) { String clusterName = (String) resource.getPropertyValue(clusterNamePropertyId); String hostName = (String) resource.getPropertyValue(hostNamePropertyId); String publicHostName = (String) resource.getPropertyValue(publicHostNamePropertyId); String componentName = (String) resource.getPropertyValue(componentNamePropertyId); if (clusterName != null && hostName != null && componentName != null && httpPropertyRequests.containsKey(componentName)) { try { Cluster cluster = clusters.getCluster(clusterName); List<HttpPropertyRequest> httpPropertyRequestList = httpPropertyRequests.get(componentName); for (HttpPropertyRequest httpPropertyRequest : httpPropertyRequestList) { populateResource(httpPropertyRequest, resource, cluster, hostName, publicHostName); } } catch (AmbariException e) { String msg = String.format("Could not load cluster with name %s.", clusterName); LOG.debug(msg, e); throw new SystemException(msg, e); } } } return resources; }
223551095_1049
@Override public Set<Resource> populateResources(Set<Resource> resources, Request request, Predicate predicate) throws SystemException { Set<String> ids = getRequestPropertyIds(request, predicate); if (ids.size() == 0) { return resources; } for (Resource resource : resources) { String clusterName = (String) resource.getPropertyValue(clusterNamePropertyId); String hostName = (String) resource.getPropertyValue(hostNamePropertyId); String publicHostName = (String) resource.getPropertyValue(publicHostNamePropertyId); String componentName = (String) resource.getPropertyValue(componentNamePropertyId); if (clusterName != null && hostName != null && componentName != null && httpPropertyRequests.containsKey(componentName)) { try { Cluster cluster = clusters.getCluster(clusterName); List<HttpPropertyRequest> httpPropertyRequestList = httpPropertyRequests.get(componentName); for (HttpPropertyRequest httpPropertyRequest : httpPropertyRequestList) { populateResource(httpPropertyRequest, resource, cluster, hostName, publicHostName); } } catch (AmbariException e) { String msg = String.format("Could not load cluster with name %s.", clusterName); LOG.debug(msg, e); throw new SystemException(msg, e); } } } return resources; }
223551095_1050
@Override public Set<Resource> getResources(Request request, Predicate predicate) throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException { Set<Resource> resourceSet = new HashSet<>(); Set<String> requestedIds = getRequestPropertyIds(request, predicate); Set<Map<String,Object>> predicatePropertieSet = getPropertyMaps(predicate); for (Map<String,Object> predicateProperties : predicatePropertieSet) { String clusterName = (String) predicateProperties .get(TASK_ATTEMPT_CLUSTER_NAME_PROPERTY_ID); String workflowId = (String) predicateProperties .get(TASK_ATTEMPT_WORKFLOW_ID_PROPERTY_ID); String jobId = (String) predicateProperties .get(TASK_ATTEMPT_JOB_ID_PROPERTY_ID); String taskAttemptId = (String) predicateProperties .get(TASK_ATTEMPT_ID_PROPERTY_ID); resourceSet.addAll(taskAttemptFetcher.fetchTaskAttemptDetails( requestedIds, clusterName, workflowId, jobId, taskAttemptId)); } return resourceSet; }
223551095_1051
@Override public Set<Resource> getResources(Request request, Predicate predicate) throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException { final Set<Resource> resources = new HashSet<>(); final Set<String> requestedIds = getRequestPropertyIds(request, predicate); final Set<Map<String, Object>> propertyMaps = getPropertyMaps(predicate); Long currentStackUniqueId = null; Map<Long, CompatibleRepositoryVersion> compatibleRepositoryVersionsMap = new HashMap<>(); StackId stackId = null; // !!! this is the case where the predicate was altered to include all stacks for (Map<String, Object> propertyMap : propertyMaps) { if (propertyMap.containsKey(REPOSITORY_STACK_VALUE)) { stackId = new StackId(propertyMap.get(REPOSITORY_STACK_VALUE).toString()); break; } } if (null == stackId) { if (propertyMaps.size() == 1) { Map<String, Object> propertyMap = propertyMaps.iterator().next(); stackId = getStackInformationFromUrl(propertyMap); } else { LOG.error("Property Maps size is NOT equal to 1. Current 'propertyMaps' size = {}", propertyMaps.size()); } } if (null == stackId) { LOG.error("Could not determine stack to process. Returning empty set."); return resources; } for (RepositoryVersionEntity repositoryVersionEntity : s_repositoryVersionDAO.findByStack(stackId)) { currentStackUniqueId = repositoryVersionEntity.getId(); compatibleRepositoryVersionsMap.put(repositoryVersionEntity.getId(), new CompatibleRepositoryVersion(repositoryVersionEntity)); if (LOG.isDebugEnabled()) { LOG.debug("Added current stack id: {} to map", repositoryVersionEntity.getId()); } } Map<String, UpgradePack> packs = s_ambariMetaInfo.get().getUpgradePacks( stackId.getStackName(), stackId.getStackVersion()); for (UpgradePack up : packs.values()) { if (null != up.getTargetStack()) { StackId targetStackId = new StackId(up.getTargetStack()); List<RepositoryVersionEntity> repositoryVersionEntities = s_repositoryVersionDAO.findByStack(targetStackId); for (RepositoryVersionEntity repositoryVersionEntity : repositoryVersionEntities) { if (compatibleRepositoryVersionsMap.containsKey(repositoryVersionEntity.getId())) { compatibleRepositoryVersionsMap.get(repositoryVersionEntity.getId()).addUpgradePackType(up.getType()); if (LOG.isDebugEnabled()) { LOG.debug("Stack id: {} exists in map. Appended new upgrade type {}{}", up.getType(), repositoryVersionEntity.getId()); } } else { CompatibleRepositoryVersion compatibleRepositoryVersionEntity = new CompatibleRepositoryVersion(repositoryVersionEntity); compatibleRepositoryVersionEntity.addUpgradePackType(up.getType()); compatibleRepositoryVersionsMap.put(repositoryVersionEntity.getId(), compatibleRepositoryVersionEntity); if (LOG.isDebugEnabled()) { LOG.debug("Added Stack id: {} to map with upgrade type {}", repositoryVersionEntity.getId(), up.getType()); } } } } else { if (currentStackUniqueId != null) { compatibleRepositoryVersionsMap.get(currentStackUniqueId).addUpgradePackType(up.getType()); if (LOG.isDebugEnabled()) { LOG.debug("Current Stack id: {} retrieved from map. Added upgrade type {}", currentStackUniqueId, up.getType()); } } else { LOG.error("Couldn't retrieve Current stack entry from Map."); } } } for (CompatibleRepositoryVersion entity : compatibleRepositoryVersionsMap.values()) { RepositoryVersionEntity repositoryVersionEntity = entity.getRepositoryVersionEntity(); final Resource resource = new ResourceImpl(Resource.Type.CompatibleRepositoryVersion); setResourceProperty(resource, REPOSITORY_VERSION_ID_PROPERTY_ID, repositoryVersionEntity.getId(), requestedIds); setResourceProperty(resource, REPOSITORY_VERSION_STACK_NAME_PROPERTY_ID, repositoryVersionEntity.getStackName(), requestedIds); setResourceProperty(resource, REPOSITORY_VERSION_STACK_VERSION_PROPERTY_ID, repositoryVersionEntity.getStackVersion(), requestedIds); setResourceProperty(resource, REPOSITORY_VERSION_DISPLAY_NAME_PROPERTY_ID, repositoryVersionEntity.getDisplayName(), requestedIds); setResourceProperty(resource, REPOSITORY_VERSION_REPOSITORY_VERSION_PROPERTY_ID, repositoryVersionEntity.getVersion(), requestedIds); setResourceProperty(resource, REPOSITORY_UPGRADES_SUPPORTED_TYPES_ID, entity.getSupportedTypes(), requestedIds); final VersionDefinitionXml xml; try { xml = repositoryVersionEntity.getRepositoryXml(); } catch (Exception e) { throw new SystemException(String.format("Could not load xml for Repository %s", repositoryVersionEntity.getId()), e); } final StackInfo stack; try { stack = s_ambariMetaInfo.get().getStack(repositoryVersionEntity.getStackName(), repositoryVersionEntity.getStackVersion()); } catch (AmbariException e) { throw new SystemException(String.format("Could not load stack %s for Repository %s", repositoryVersionEntity.getStackId().toString(), repositoryVersionEntity.getId())); } final List<ManifestServiceInfo> stackServices; if (null != xml) { setResourceProperty(resource, REPOSITORY_VERSION_SERVICES, xml.getAvailableServices(stack), requestedIds); stackServices = xml.getStackServices(stack); } else { stackServices = new ArrayList<>(); for (ServiceInfo si : stack.getServices()) { stackServices.add(new ManifestServiceInfo(si.getName(), si.getDisplayName(), si.getComment(), Collections.singleton(si.getVersion()))); } } setResourceProperty(resource, REPOSITORY_VERSION_STACK_SERVICES, stackServices, requestedIds); resources.add(resource); } return resources; }
223551095_1052
@Override public Set<Resource> getResources(Request request, Predicate predicate) throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException { Set<Resource> resourceSet = new HashSet<>(); Set<String> requestedIds = getRequestPropertyIds(request, predicate); Set<Map<String,Object>> predicatePropertieSet = getPropertyMaps(predicate); for (Map<String,Object> predicateProperties : predicatePropertieSet) { String clusterName = (String) predicateProperties .get(WORKFLOW_CLUSTER_NAME_PROPERTY_ID); String workflowId = (String) predicateProperties .get(WORKFLOW_ID_PROPERTY_ID); resourceSet.addAll(workflowFetcher.fetchWorkflows(requestedIds, clusterName, workflowId)); } return resourceSet; }
223551095_1053
@Override public Set<Resource> getResources(Request request, Predicate predicate) throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException { Set<Resource> resourceSet = new HashSet<>(); Set<String> requestedIds = getRequestPropertyIds(request, predicate); Set<Map<String,Object>> predicatePropertieSet = getPropertyMaps(predicate); for (Map<String,Object> predicateProperties : predicatePropertieSet) { String clusterName = (String) predicateProperties .get(WORKFLOW_CLUSTER_NAME_PROPERTY_ID); String workflowId = (String) predicateProperties .get(WORKFLOW_ID_PROPERTY_ID); resourceSet.addAll(workflowFetcher.fetchWorkflows(requestedIds, clusterName, workflowId)); } return resourceSet; }
223551095_1054
@Override public Set<Resource> getResources(Request request, Predicate predicate) throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException { final Set<StackRequest> requests = new HashSet<>(); if (predicate == null) { requests.add(getRequest(Collections.emptyMap())); } else { for (Map<String, Object> propertyMap : getPropertyMaps(predicate)) { requests.add(getRequest(propertyMap)); } } Set<String> requestedIds = getRequestPropertyIds(request, predicate); Set<StackResponse> responses = getResources(new Command<Set<StackResponse>>() { @Override public Set<StackResponse> invoke() throws AmbariException { return getManagementController().getStacks(requests); } }); Set<Resource> resources = new HashSet<>(); for (StackResponse response : responses) { Resource resource = new ResourceImpl(Resource.Type.Stack); setResourceProperty(resource, STACK_NAME_PROPERTY_ID, response.getStackName(), requestedIds); resource.setProperty(STACK_NAME_PROPERTY_ID, response.getStackName()); resources.add(resource); } return resources; }
223551095_1055
@Override public Set<String> getHostNames(String clusterName, String componentName) { return overridenJmxUri(componentName) .map(uri -> singleton(resolve(uri, clusterName).getHost())) .orElseGet(() -> defaultProvider.getHostNames(clusterName, componentName)); }
223551095_1056
public HttpURLConnection processURL(String spec, String requestMethod, String body, Map<String, List<String>> headers) throws IOException { return processURL(spec, requestMethod, body == null ? null : body.getBytes(), headers); }
223551095_1057
public HttpURLConnection processURL(String spec, String requestMethod, String body, Map<String, List<String>> headers) throws IOException { return processURL(spec, requestMethod, body == null ? null : body.getBytes(), headers); }
223551095_1059
protected Set<HostResponse> getHosts(Set<HostRequest> requests) throws AmbariException { Set<HostResponse> response = new HashSet<>(); AmbariManagementController controller = getManagementController(); for (HostRequest request : requests) { try { response.addAll(getHosts(controller, request, osFamily)); } catch (HostNotFoundException e) { if (requests.size() == 1) { // only throw exception if 1 request. // there will be > 1 request in case of OR predicate throw e; } } } return response; }
223551095_1060
protected Set<HostResponse> getHosts(Set<HostRequest> requests) throws AmbariException { Set<HostResponse> response = new HashSet<>(); AmbariManagementController controller = getManagementController(); for (HostRequest request : requests) { try { response.addAll(getHosts(controller, request, osFamily)); } catch (HostNotFoundException e) { if (requests.size() == 1) { // only throw exception if 1 request. // there will be > 1 request in case of OR predicate throw e; } } } return response; }
223551095_1061
protected Set<HostResponse> getHosts(Set<HostRequest> requests) throws AmbariException { Set<HostResponse> response = new HashSet<>(); AmbariManagementController controller = getManagementController(); for (HostRequest request : requests) { try { response.addAll(getHosts(controller, request, osFamily)); } catch (HostNotFoundException e) { if (requests.size() == 1) { // only throw exception if 1 request. // there will be > 1 request in case of OR predicate throw e; } } } return response; }