Builds RocksDb {@link WriteOptions}.

@param sync
As of RocksDB v3.10.1, no data lost if process crashes even if sync==false. Data
lost only when server/OS crashes. So it's relatively safe to set sync=false for
fast write
@param disableWAL
@return
193490
public static WriteOptions buildWriteOptions(boolean sync, boolean disableWAL) {
        WriteOptions writeOptions = new WriteOptions();
        writeOptions.setSync(sync).setDisableWAL(disableWAL);
        return writeOptions;
    }
80863
@Override
    public void setRollbackOnly(String globalId) throws SystemException {

        final DistributableTransaction tx = getTransactionForID(globalId);

        if (tx != null) {
            tx.setRollbackOnly();
        }
    }
987711
@Deprecated
    public synchronized GoConfigSaveResult writeWithLock(UpdateConfigCommand updatingCommand, GoConfigHolder configHolder) {
        try {

            // Need to convert to xml before we try to write it to the config file.
            // If our cruiseConfig fails XSD validation, we don't want to write it incorrectly.
            GoConfigHolder validatedConfigHolder;

            List<PartialConfig> lastKnownPartials = cachedGoPartials.lastKnownPartials();
            List<PartialConfig> lastValidPartials = cachedGoPartials.lastValidPartials();
            try {
                validatedConfigHolder = trySavingConfig(updatingCommand, configHolder, lastKnownPartials);
                updateMergedConfigForEdit(validatedConfigHolder, lastKnownPartials);
            } catch (Exception e) {
                if (lastKnownPartials.isEmpty() || areKnownPartialsSameAsValidPartials(lastKnownPartials, lastValidPartials)) {
                    throw e;
                } else {
                    LOGGER.warn("Merged config update operation failed on LATEST {} partials. Falling back to using LAST VALID {} partials. Exception message was: {}", lastKnownPartials.size(), lastValidPartials.size(), e.getMessage(), e);
                    try {
                        validatedConfigHolder = trySavingConfig(updatingCommand, configHolder, lastValidPartials);
                        updateMergedConfigForEdit(validatedConfigHolder, lastValidPartials);
                        LOGGER.info("Update operation on merged configuration succeeded with old {} LAST VALID partials.", lastValidPartials.size());
                    } catch (GoConfigInvalidException fallbackFailed) {
                        LOGGER.warn("Merged config update operation failed using fallback LAST VALID {} partials. Exception message was: {}", lastValidPartials.size(), fallbackFailed.getMessage(), fallbackFailed);
                        throw new GoConfigInvalidMergeException(lastValidPartials, fallbackFailed);
                    }
                }
            }
            ConfigSaveState configSaveState = shouldMergeConfig(updatingCommand, configHolder) ? ConfigSaveState.MERGED : ConfigSaveState.UPDATED;
            return new GoConfigSaveResult(validatedConfigHolder, configSaveState);
        } catch (ConfigFileHasChangedException e) {
            LOGGER.warn("Configuration file could not be merged successfully after a concurrent edit: {}", e.getMessage(), e);
            throw e;
        } catch (GoConfigInvalidException e) {
            LOGGER.warn("Configuration file is invalid: {}", e.getMessage(), e);
            throw bomb(e.getMessage(), e);
        } catch (Exception e) {
            LOGGER.error("Configuration file is not valid: {}", e.getMessage(), e);
            throw bomb(e.getMessage(), e);
        } finally {
            LOGGER.debug("[Config Save] Done writing with lock");
        }
    }
809767
public int writeDependency(Object id,
                               ValueSet valueSet) {
        final String methodName = "writeDependency()";
        int rc = NO_EXCEPTION;
        if (valueSet.size() == 0) {
            if (tc.isDebugEnabled())
                Tr.debug(tc, methodName, "cacheName=" + this.cacheName + " valueSet=0");
        }
        if (!this.disableDependencyId) {
            if (delayOffload) {
                ValueSet vs = auxDataDependencyTable.getEntries(id);
                if (vs == null) {
                    if (valueSet.size() <= auxDataDependencyTable.delayOffloadEntriesLimit) {
                        Result result = writeValueSetEntry(DEP_ID_DATA, id, null, valueSet, !ADD_IF_NEW);
                        rc = result.returnCode;
                        boolean bComplete = result.bComplete;
                        returnToResultPool(result);
                        if (rc != DISK_EXCEPTION && !bComplete) {
                            rc = auxDataDependencyTable.add(id, valueSet);
                        }
                    } else {
                        rc = writeValueSet(DEP_ID_DATA, id, valueSet, !ALL); // valueSet may be empty after writeValueSet
                        this.cache.getCacheStatisticsListener().depIdsOffloadedToDisk(id);
                    }
                } else {
                    vs.union(valueSet);
                    if (vs.size() > auxDataDependencyTable.delayOffloadEntriesLimit) {
                        auxDataDependencyTable.removeDependency(id);
                        rc = writeValueSet(DEP_ID_DATA, id, vs, ALL); // valueSet may be empty after writeValueSet
                        if (rc != NO_EXCEPTION) {
                            valueSet.clear();
                            valueSet.addAll(vs);
                        }
                        this.cache.getCacheStatisticsListener().depIdsOffloadedToDisk(id);
                    }
                }
            } else {
                rc = writeValueSet(DEP_ID_DATA, id, valueSet, !ALL); // valueSet may be empty after writeValueSet
            }
        }
        return rc;
    }
312106
@Override
    public WRITE_ACTION writeOrAddToQ(H2WriteQEntry entry) throws FlowControlException {
        synchronized (qSync) {

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "process write entry with qStatus: " + qStatus + " entry: " + entry.hashCode());
            }
            if (entry.getFrameType() == FrameTypes.DATA) {
                decreaseConnectionWindowUpdateWriteLimit(entry.getPayloadLength());
            }

            if (qStatus == Q_STATUS.NOT_IN_USE) {
                // perform the write on this thread, outside the sync block
                qStatus = Q_STATUS.BYPASSED;
                entry.setServicedOnQ(false);

            } else if ((qStatus == Q_STATUS.ACTIVE) || (qStatus == Q_STATUS.STAND_BY)) {
                // queue is in use, so add this write entry to the queue/tree and leave
                entry.setServicedOnQ(true);
                addEntryToQ(entry);
                return WRITE_ACTION.QUEUED;

            } else if (qStatus == Q_STATUS.BYPASSED) {
                // queue is not in use, but needs to be now, since we are want to write with a write outstanding.
                entry.setServicedOnQ(true);
                qStatus = Q_STATUS.STAND_BY;
                addEntryToQ(entry);
                // wait for outstanding request to complete before allowing the queue thread to make more write requests
                try {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "waiting to start write Q thread");
                    }
                    qSync.wait();
                    qStatus = Q_STATUS.ACTIVE;
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "start write Q thread");
                    }
                    startQThread();
                    return WRITE_ACTION.QUEUED;
                } catch (InterruptedException e) {
                    // TODO: handle this somehow
                }

            } else if ((qStatus == Q_STATUS.QUIT) || (qStatus == Q_STATUS.FINISHED)) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "do not process write - Q told to quit");
                }
                return WRITE_ACTION.CONNECTION_QUIT;
            }
        } // end synchronized

        // Determined from above that we are to handle this write on the callers thread
        if (!(entry.getServicedOnQ())) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "perform write on caller's thread");
            }
            return writeEntry(entry);
        }

        // should never get here
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "uh-oh we're confused: WRITE_ACTION.CONFUSED");
        }
        return WRITE_ACTION.CONFUSED;
    }
7274
func (opts *WriteOptions) DisableWAL(value bool) {
	C.rocksdb_writeoptions_disable_WAL(opts.c, C.int(btoi(value)))
}
662140
@Override
    public boolean addSync() throws ResourceException {

        if (tc.isEntryEnabled()) {
            Tr.entry(this, tc, "addSync");
        }

        try {

            UOWCoordinator uowCoord = mcWrapper.getUOWCoordinator();
            if (uowCoord != null) {
                if (uowCoord.isGlobal()) {
                    if (mcWrapper.isConnectionSynchronizationProvider()) {
                        throw new UnsupportedOperationException("com.ibm.ws.Transaction.SynchronizationProvider");
                        /*
                         * Use the Synchronization object from the managed connection to
                         * register.
                         */
                        //Synchronization s = ((SynchronizationProvider)mcWrapper.getManagedConnection()).getSynchronization();
                        //LocationSpecificFunction.instance.getTransactionManager().registerSynchronization(uowCoord, s, EmbeddableWebSphereTransactionManager.SYNC_TIER_INNER);
                    }
                    /*
                     * This code will remain here just in case we run into this
                     * case. We should not be isEnlistmentDisabled in this code.
                     *
                     * Log a message and return, if isEnlistmentDisabled is true.
                     */
                    if (mcWrapper.isEnlistmentDisabled()) {
                        if (tc.isDebugEnabled()) {
                            Tr.debug(this, tc, "Managed connection isEnlistmentDisabled is true.");
                            Tr.debug(this, tc, "Returning without registering.");
                        }
                        if (tc.isEntryEnabled()) {
                            Tr.exit(this, tc, "addSync", false);
                        }
                        return false;
                    }
                    /*
                     * Use our XATransactionWrapper
                     */
                    // Global Transaction
                    EmbeddableWebSphereTransactionManager tranMgr = mcWrapper.pm.connectorSvc.transactionManager;
                    tranMgr.registerSynchronization(uowCoord, this);
                    mcWrapper.markLocalTransactionWrapperInUse();
                    registeredForSync = true;
                } else {
                    // Local Transaction
                    // No need to register for synchronization for unshared/LTC/res-control=Application.
                    //  Instead of cleanup being done via after completion it will either happen at close or
                    //  commit/rollback which ever happens last.  This will allow the connection to be returned
                    //  to the pool prior to the end of the LTC scope allowing better utilization of the connection.
                    boolean shareable = mcWrapper.getConnectionManager().shareable();
                    if (!shareable && !J2CUtilityClass.isContainerAtBoundary(mcWrapper.pm.connectorSvc.transactionManager)) {
                        // Register an instance of an RRS no-transaction wrapper
                        // so the TM will create an RRS NativeLocalTranasction.  The wrapper
                        // provides "empty" TransactioWrapper and Synchronization behaviors,
                        // but indicates to the TM that the LTC requires RRS support.

                        //if (tc.isEntryEnabled()) {
                        //  Tr.exit(this, tc, "addSync: returning without registering.");
                        //}
                        //return false;
                        if (this.isRRSTransactional()) {
                            ((SynchronizationRegistryUOWScope) uowCoord).registerInterposedSynchronization(
                                                                                                           new RRSNoTransactionWrapper());
                        } else {
                            if (tc.isEntryEnabled()) {
                                Tr.exit(this, tc, "addSync", "returning without registering");
                            }
                            return false;
                        }
                    } else {

                        if (mcWrapper.isConnectionSynchronizationProvider()) {
                            throw new UnsupportedOperationException("com.ibm.ws.Transaction.SynchronizationProvider");
                            /*
                             * Use the Synchronization object from the managed connection to
                             * register.
                             */
                            //Synchronization s = ((SynchronizationProvider)mcWrapper.getManagedConnection()).getSynchronization();
                            //((SynchronizationRegistryUOWScope) uowCoord).registerInterposedSynchronization(s);
                            //registeredForSync = false;
                        } else {

                            /*
                             * In order
                             * to take advantage of the new level of code in which MCWrapper has the isEnlistmentDisabled()
                             */
                            if (mcWrapper.isEnlistmentDisabled()) {
                                if (tc.isDebugEnabled()) {
                                    Tr.debug(this, tc, "Managed connection isEnlistmentDisabled is true.");
                                    Tr.debug(this, tc, "Returning without registering.");
                                }
                                if (tc.isEntryEnabled()) {
                                    Tr.exit(this, tc, "addSync", false);
                                }
                                return false;
                            }
                            ((SynchronizationRegistryUOWScope) uowCoord).registerInterposedSynchronization(this);
                            mcWrapper.markLocalTransactionWrapperInUse();
                            registeredForSync = true;
                        }

                    }
                }
            } else {
                // No transaction context.  Should never happen.
                Tr.error(tc, "NO_VALID_TRANSACTION_CONTEXT_J2CA0040", "addSync", null, mcWrapper.gConfigProps.cfName);
                throw new ResourceException("INTERNAL ERROR: No valid transaction context present");
            }

        } catch (ResourceException e) {
            com.ibm.ws.ffdc.FFDCFilter.processException(
                                                        e,
                                                        "com.ibm.ejs.j2c.LocalTransactionWrapper.addSync",
                                                        "594",
                                                        this);
            Tr.error(tc, "REGISTER_WITH_SYNCHRONIZATION_EXCP_J2CA0026", "addSync", e, "Exception");
            throw e;
        } catch (Exception e) {
            com.ibm.ws.ffdc.FFDCFilter.processException(
                                                        e,
                                                        "com.ibm.ejs.j2c.LocalTransactionWrapper.addSync",
                                                        "605",
                                                        this);
            Tr.error(tc, "REGISTER_WITH_SYNCHRONIZATION_EXCP_J2CA0026", "addSync", e, "Exception");
            ResourceException re = new ResourceException("addSync: caught Exception");
            re.initCause(e);
            throw re;
        }
        if (tc.isEntryEnabled()) {
            Tr.exit(this, tc, "addSync", registeredForSync);
        }

        return registeredForSync;

    }
206316
@SuppressWarnings("unchecked")
	private void privateSync(final boolean syncInternal, final boolean forceSyncStore) {
		if (readOnly) {
			return;
		}
		final long ts = System.currentTimeMillis();
		boolean isDirty = false;
		if (!dirtyLeafNodes.isEmpty() || !dirtyInternalNodes.isEmpty()) {
			submitRedoMeta(0); // Meta Sync (full recover needed)
		}
		//
		// Write Leaf Nodes
		if (!dirtyLeafNodes.isEmpty()) {
			isDirty = true;
			final Node<K, V>[] dirtyBlocks = dirtyLeafNodes.getValues();
			Arrays.sort(dirtyBlocks, dirtyComparatorByID);
			for (Node<K, V> node : dirtyBlocks) {
				if (node == null) {
					break;
				}
				// if (log.isDebugEnabled()) log.debug("node.id=" + node.id);
				dirtyLeafNodes.remove(node.id);
				putNodeToStore(node);
				if (!node.isDeleted()) {
					cacheLeafNodes.put(node.id, node);
				}
			}
			if (!dirtyLeafNodes.isEmpty()) {
				dirtyLeafNodes.clear(false); // Clear without shrink
			}
		}
		// Write Internal Nodes
		if (syncInternal && !dirtyInternalNodes.isEmpty()) {
			isDirty = true;
			final Node<K, V>[] dirtyBlocks = dirtyInternalNodes.getValues();
			Arrays.sort(dirtyBlocks, dirtyComparatorByID);
			for (Node<K, V> node : dirtyBlocks) {
				if (node == null) {
					break;
				}
				// if (log.isDebugEnabled()) log.debug("node.id=" + node.id);
				dirtyInternalNodes.remove(node.id);
				putNodeToStore(node);
				if (!node.isDeleted()) {
					cacheInternalNodes.put(node.id, node);
				}
			}
			if (!dirtyInternalNodes.isEmpty()) {
				dirtyInternalNodes.clear(false); // Clear without shrink
			}
		}
		//
		if (isDirty) {
			writeMetaData(false);
			if (forceSyncStore || !disableAutoSyncStore)
				storage.sync();
			redoQueue.clear();
			redoStore.clear();
		}
		if (log.isDebugEnabled()) {
			final StringBuilder sb = new StringBuilder();
			// @formatter:off
			sb
			.append(this.getClass().getName()).append("::sync()")
			.append(" elements=").append(elements)
			.append(" Int=").append(maxInternalNodes)
			.append(" Leaf=").append(maxLeafNodes)
			.append(" dirty{")
			.append(" Int=").append(dirtyInternalNodes.size())
			.append(" Leaf=").append(dirtyLeafNodes.size())
			.append(" }")
			.append(" cache{")
			.append(" Int=").append(cacheInternalNodes.size())
			.append(" Leaf=").append(cacheLeafNodes.size())
			.append(" }")
			.append(" storage{")
			.append(" total=").append(storage.sizeInBlocks())
			.append(" free=").append(freeBlocks.cardinality())
			.append(" }")
			.append(" time=").append(System.currentTimeMillis() - ts);
			// @formatter:on
			log.debug(sb.toString());
		}
		// clearWriteCaches();
	}
379120
def sync_blockchain( working_dir, bt_opts, last_block, server_state, expected_snapshots={}, **virtualchain_args ):
    
    
    subdomain_index = server_state['subdomains']
    atlas_state = server_state['atlas']
    
    # make this usable even if we haven't explicitly configured virtualchain 
    impl = sys.modules[__name__]
    log.info("Synchronizing database {} up to block {}".format(working_dir, last_block))

    # NOTE: this is the only place where a read-write handle should be created,
    # since this is the only place where the db should be modified.
    new_db = BlockstackDB.borrow_readwrite_instance(working_dir, last_block, expected_snapshots=expected_snapshots)

    # propagate runtime state to virtualchain callbacks
    new_db.subdomain_index = subdomain_index
    new_db.atlas_state = atlas_state
    
    rc = virtualchain.sync_virtualchain(bt_opts, last_block, new_db, expected_snapshots=expected_snapshots, **virtualchain_args)
    
    BlockstackDB.release_readwrite_instance(new_db, last_block)

    return rc
503991
public synchronized void write(final boolean forceSync) throws IOException {
		if (!validState) {
			throw new InvalidStateException();
		}
		buf.clear();
		buf.putLong(value);
		buf.flip();
		fc.position(fc.size()).write(buf); // go end and write
		if (forceSync) {
			fc.force(false);
		}
	}
509087
public int syncRecords()
    { // Read a valid record
        if ((this.getOwner().getOpenMode() & DBConstants.OPEN_DONT_CHANGE_CURRENT_LOCK_TYPE) == DBConstants.OPEN_DONT_CHANGE_CURRENT_LOCK_TYPE)
            return DBConstants.NORMAL_RETURN;   // Don't need to resync if I'm doing a write and refresh.
        m_recordToSync.close();
        return DBConstants.NORMAL_RETURN;
    }
850009
public void put(String cfName, WriteOptions writeOptions, String key, byte[] value)
            throws RocksDbException {
        if (cfName == null) {
            cfName = DEFAULT_COLUMN_FAMILY;
        }
        try {
            put(columnFamilyHandles.get(cfName), writeOptions, key.getBytes(StandardCharsets.UTF_8),
                    value);
        } catch (RocksDbException.ColumnFamilyNotExists e) {
            throw new RocksDbException.ColumnFamilyNotExists(cfName);
        }
    }
1355139
public static RocksDbWrapper openReadOnly(String dirPath, DBOptions dbOptions,
            ReadOptions readOptions) throws RocksDbException, IOException {
        RocksDbWrapper rocksDbWrapper = new RocksDbWrapper(dirPath, true);
        rocksDbWrapper.setDbOptions(dbOptions).setReadOptions(readOptions);
        rocksDbWrapper.init();
        return rocksDbWrapper;
    }
929893
static RolloutOptions rolloutOptionsWithFallback(final RolloutOptions options, final Job job) {
    return options.withFallback(
        job.getRolloutOptions() == null
        ? RolloutOptions.getDefault()
        : job.getRolloutOptions().withFallback(RolloutOptions.getDefault()));
  }
770633
@Deprecated
   public PartitionHandlingConfigurationBuilder enabled(boolean enabled) {
      whenSplit(enabled ? PartitionHandling.DENY_READ_WRITES : PartitionHandling.ALLOW_READ_WRITES);
      mergePolicy(MergePolicy.NONE);
      return this;
   }
296054
def enable_writes(self):
        """"""
        self.write_buffer = []
        self.flush_lock = threading.RLock()
        self.flush_thread = FlushThread(self.max_batch_time,
                                        self._flush_writes)
531603
function writeSync(description, options) {
  var file = vfile(description)
  fs.writeFileSync(
    path.resolve(file.cwd, file.path),
    file.contents || '',
    options
  )
}