http://guide.couchdb.org/draft/replication.html
512937
function queryReplication (id, opts0, callback0) {
    const { opts, callback } = getCallback(opts0, callback0)
    return relax({ db: '_replicator', method: 'GET', path: id, qs: opts }, callback)
  }
1046226
def curl_couchdb(url, method='GET', base_url=BASE_URL, data=None):
    '''
        
    '''
    (username, password) = get_admin()
    if username is None:
        auth = None
    else:
        auth = (username, password)

    if method == 'PUT':
        req = requests.put('{}{}'.format(base_url, url), auth=auth, data=data)
    elif method == 'DELETE':
        req = requests.delete('{}{}'.format(base_url, url), auth=auth)
    else:
        req = requests.get('{}{}'.format(base_url, url), auth=auth)

    if req.status_code not in [200, 201]:
        raise HTTPError('{}: {}'.format(req.status_code, req.text))
    return req
3945
def info(self):
        """"""
        hosts = ','.join(x['host'] for x in self.members())
        mongodb_uri = 'mongodb://' + hosts + '/?replicaSet=' + self.repl_id
        result = {"id": self.repl_id,
                  "auth_key": self.auth_key,
                  "members": self.members(),
                  "mongodb_uri": mongodb_uri,
                  "orchestration": 'replica_sets'}
        if self.login:
            # Add replicaSet URI parameter.
            uri = ('%s&replicaSet=%s'
                   % (self.mongodb_auth_uri(hosts), self.repl_id))
            result['mongodb_auth_uri'] = uri
        return result
231969
function (config) {
        if (!config) { return; }

        var replConfig,
            peerNames,

            sanitisePeerConfig,
            source = this.sources[config.identity]; // fn

        // at this stage, the source should not be there
        if (source) {
            source.end(); // in case sources exist (almost unlikely, end them)
            console.log('Warn: duplicate setup of connection found in replication setup for ' + config.identity);
        }

        // set default for configuration objects and also clone them
        // ---------------------------------------------------------

        // clone and set defaults for the configuration variables.
        config = util.clone(config); // clone config. do it here to clone replication config too
        replConfig = util.fill(config.replication || {
            enabled: false // blank config means replication disabled
        }, DEFAULT_REPL_SOURCE_CFG); // extract repl config from main config

        !replConfig.sources && (replConfig.sources = {}); // set default to no source if none specified
        delete config.replication; // we remove the recursive config from main config clone.

        // setup a dumb source as a precaution and since we should fall back to original connection if setup fails
        source = this.sources[config.identity] = db.oneDumbSource();

        // replication explicitly disabled or no peers defined. we do this after ending any ongoing sources
        source._replication = !!replConfig.enabled;
        if (source._replication === false) {
            return;
        }

        // create default connection parameters for cluster
        // ------------------------------------------------

        // get the list of peer names defined in sources and setup the config defaults for peer sources
        peerNames = _.filter(Object.keys(replConfig.sources) || [], function (peer) { // remove all disabled peers
            return (peer = replConfig.sources[peer]) && (peer.enabled !== false);
        });

        sanitisePeerConfig = function (peerConfig) {
            return util.fill(util.extend(peerConfig, {
                database: peerConfig._database || config.database, // force db name to be same
                pool: true,
                waitForConnections: true,
                multipleStatements: true
            }), (replConfig.inheritMaster === true) && config);
        };

        // depending upon the number of peers defined, create simple connection or clustered connection
        // --------------------------------------------------------------------------------------------

        // nothing much to do, if there are no replication source defined
        if (peerNames.length === 0) {
            sails && sails.log.info('smt is re-using master as readonly source');
            // if it is marked to inherit master in replication, we simply create a new source out of the master config
            if (replConfig.inheritMaster === true) {
                this.sources[config.identity] = db.createSource(sanitisePeerConfig({}));
            }
            return;
        }

        // for a single peer, the configuration is simple, we do not need a cluster but a simple pool
        if (peerNames.length === 1) {
            sails && sails.log.info('smt is using 1 "' + config.identity + '" readonly source - ' + peerNames[0]);
            // ensure that the single source's config is taken care of by setting the default and if needed inheriting
            // from master
            this.sources[config.identity] = db.createSource(sanitisePeerConfig(replConfig.sources[peerNames[0]]));
            return;
        }

        // iterate over all sources and normalise and validate their configuration
        util.each(replConfig.sources, sanitisePeerConfig);
        sails && sails.log.info('smt is using ' + peerNames.length + ' "' + config.identity + '" readonly sources - ' +
            peerNames.join(', '));

        // create connections for read-replicas and add it to the peering list
        this.sources[config.identity] = db.createCluster(replConfig);
    }
917469
public List<InetAddress> replicaNodesForId(final String id) {
        BucketConfig config = bucketConfig.get();

        if (config instanceof CouchbaseBucketConfig) {
            CouchbaseBucketConfig cbc = (CouchbaseBucketConfig) config;
            List<InetAddress> replicas = new ArrayList<InetAddress>();
            for (int i = 1; i <= cbc.numberOfReplicas(); i++) {
                replicas.add(replicaNodeForId(id, i));
            }
            return replicas;
        } else {
            throw new UnsupportedOperationException("Bucket type not supported: " + config.getClass().getName());
        }
    }
89023
public com.cloudant.client.api.model.ReplicationResult trigger() {
        ReplicationResult couchDbReplicationResult = replication.trigger();
        com.cloudant.client.api.model.ReplicationResult replicationResult = new com.cloudant
                .client.api.model.ReplicationResult(couchDbReplicationResult);
        return replicationResult;
    }
740347
def setup_db(self, couch, dbname):
        

        # Avoid race condition of two creating db
        my_db = None

        self.log.debug('Setting up DB: %s' % dbname)

        if dbname not in couch:
            self.log.info("DB doesn't exist so creating DB: %s", dbname)
            try:
                my_db = couch.create(dbname)
            except:
                self.log.critical("Race condition caught")
                raise RuntimeError("Race condition caught when creating DB")

            try:
                auth_doc = {}
                auth_doc['_id'] = '_design/auth'
                auth_doc['language'] = 'javascript'

                auth_doc['validate_doc_update'] = """
                function(newDoc, oldDoc, userCtx) {
                if (userCtx.roles.indexOf('_admin') !== -1) {
                return;
                } else {
                throw({forbidden: 'Only admins may edit the database'});
                }
                }
                """

                my_db.save(auth_doc)
            except:
                self.log.error('Could not set permissions of %s' % dbname)

        else:
            my_db = couch[dbname]

        return my_db
256975
protected void start() {
        try {
            if (!db.isOpen()) {
                String msg = String.format(Locale.ENGLISH, "Db: %s is not open, abort replication", db);
                parentReplication.setLastError(new Exception(msg));
                fireTrigger(ReplicationTrigger.STOP_IMMEDIATE);
                return;
            }
            db.addActiveReplication(parentReplication);
            this.authenticating = false;
            initSessionId();
            // initialize batcher
            initBatcher();
            // initialize authorizer / authenticator
            initAuthorizer();
            // initialize request workers
            initializeRequestWorkers();
            // reset lastSequence
            // https://github.com/couchbase/couchbase-lite-java-core/issues/1623
            this.lastSequence = null;
            // single-shot replication
            if (!isContinuous())
                goOnline();
                // continuous mode
            else {
                if (isNetworkReachable())
                    goOnline();
                else
                    triggerGoOffline();
                startNetworkReachabilityManager();
            }
        } catch (Exception e) {
            Log.e(Log.TAG_SYNC, "%s: Exception in start()", e, this);
        }
    }
56000
private void addProperties(ReplicationInternal replicationInternal) {
        for (ReplicationField key : properties.keySet()) {
            Object value = properties.get(key);
            switch (key) {
                case FILTER_NAME:
                    replicationInternal.setFilter((String) value);
                    break;
                case FILTER_PARAMS:
                    replicationInternal.setFilterParams((Map) value);
                    break;
                case DOC_IDS:
                    replicationInternal.setDocIds((List) value);
                    break;
                case AUTHENTICATOR:
                    replicationInternal.setAuthenticator((Authenticator) value);
                    break;
                case CREATE_TARGET:
                    replicationInternal.setCreateTarget((Boolean) value);
                    break;
                case REQUEST_HEADERS:
                    replicationInternal.setHeaders((Map) value);
                    break;
                case REMOTE_UUID:
                    replicationInternal.setRemoteUUID((String) value);
                    break;
                case CHANNELS:
                    replicationInternal.setChannels((List<String>)value);
                    break;
            }
        }
    }
1224271
function CouchDB () {
  var self = this;

  self.klass = CouchDB;
  self.klass.super_.apply(self, arguments);

  if (self.options.server.protocol === 'https') {
    self.options.server.port = self.options.server.port || 443;
    self.options.server.secure = true;
  }

  if (self.options.server.username || self.options.server.password) {
    self.options.client.auth = {
      username: self.options.server.username,
      password: self.options.server.password
    };
  }
}
1026930
public Status do_GET_Database(Database _db, String _docID, String _attachmentName) {
        // http://wiki.apache.org/couchdb/HTTP_database_API#Database_Information
        Status status = openDB();
        if (!status.isSuccessful()) {
            return status;
        }
        // NOTE: all methods are read operation. not necessary to be synchronized
        int num_docs = db.getDocumentCount();
        long update_seq = db.getLastSequenceNumber();
        long instanceStartTimeMicroseconds = db.getStartTime() * 1000;
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("db_name", db.getName());
        result.put("db_uuid", db.publicUUID());
        result.put("doc_count", num_docs);
        result.put("update_seq", update_seq);
        result.put("disk_size", db.totalDataSize());
        result.put("instance_start_time", instanceStartTimeMicroseconds);

        connection.setResponseBody(new Body(result));
        return new Status(Status.OK);
    }
80683
function (config) {
        // at this stage, the `db` variable should not exist. expecting fresh setup or post teardown setup.
        if (Transaction.databases[config.identity]) {
            // @todo - emit wrror event instead of console.log
            console.log('Warn: duplicate setup of connection found in Transactions.setup');
            this.teardown();
        }

        var _db;

        // clone the configuration
        config = util.clone(config);
        delete config.replication;

        // allow special transaction related config
        util.each(config, function (value, name, config) {
            if (!/^transaction.+/g.test(name)) { return; }

            // remove transaction config prefix
            var baseName = name.replace(/^transaction/g, '');
            baseName = baseName.charAt(0).toLowerCase() + baseName.slice(1);

            delete config[name];
            config[baseName] = value;
        });

        _db = db.createSource(config);

        // Save a few configurations
        _db && (_db.transactionConfig = {
            rollbackOnError: config.rollbackTransactionOnError
        });

        Transaction.databases[config.identity] = _db;
    }
357685
def create(self):
        

        # Ensure that an existing document will not be "updated"
        doc = dict(self)
        if doc.get('_rev') is not None:
            doc.__delitem__('_rev')

        headers = {'Content-Type': 'application/json'}
        resp = self.r_session.post(
            self._database.database_url,
            headers=headers,
            data=json.dumps(doc, cls=self.encoder)
        )
        resp.raise_for_status()
        data = response_to_json_dict(resp)
        super(Document, self).__setitem__('_id', data['id'])
        super(Document, self).__setitem__('_rev', data['rev'])
484229
def db(context, data):
    """"""
    table = context.params.get("table", context.crawler.name)
    params = context.params
    params["table"] = table
    _recursive_upsert(context, params, data)
349451
function(callback) { // # 1

          var startReplicas = Math.pow(Number(self.conf.balancing['REPLICA_BASE_NUMBER']), Number(self.conf.balancing['MAX_LEVEL']));

          var address = '';
          if (self.conf.zookeeper) {
            if (typeof self.conf.zookeeper === 'string' || self.conf.zookeeper instanceof String) {
              address = self.conf.zookeeper;
            } else {
              if (self.conf.zookeeper.address) address = self.conf.zookeeper.address;
            }
          }

          self.nodeManager = new NodeManager(
            address,
            false,
            function(err, message) {
              if (!err) {
                console.info(' (init) ZOOKEEPER is connected');
                self.nodeManager.addServerNode(self.conf, startReplicas, function(err, path, replicas) {

                  //if (!err) console.info('        ZOOKEEPER /' + self.conf.host + ':' + self.conf.port);

                  var serverName = path.substring(path.lastIndexOf('/') + 1, path.length);
                  self.serverNodePath = path;

                  self.serverName = serverName.split('^')[0];

                  if (replicas) {
                    self.replicas = replicas;
                  } else {
                    self.replicas = startReplicas;
                  }

                  // init balacing config
                  self.nodeManager.getConfigInfo('balancing', function(data) {
                    if (data) {

                      self.conf.balancing = data;
                      var configReplica = Math.pow(Number(self.conf.balancing['REPLICA_BASE_NUMBER']), Number(self.conf.balancing['MAX_LEVEL']));

                      if (self.replicas != configReplica) {
                        self._changeReplicas(configReplica);
                      }
                    }
                  });

                  callback(err);
                });
              } else {
                callback(err, message);
              }
            }
          );
        }
943340
def replicate(ctx, args):
    
    slave = ClusterNode.from_uri(args.node)
    master = ClusterNode.from_uri(args.master)
    if not master.is_master():
        ctx.abort("Node {!r} is not a master.".format(args.master))

    try:
        slave.replicate(master.name)
    except redis.ResponseError as e:
        ctx.abort(str(e))

    Cluster.from_node(master).wait()
859652
function connect (state) {
  return Promise.resolve(state.remote)

  .then(function (remote) {
    if (state.replication) {
      return
    }

    state.replication = state.db.sync(remote, {
      create_target: true,
      live: true,
      retry: true
    })

    state.replication.on('error', function (error) {
      state.emitter.emit('error', error)
    })

    state.replication.on('change', function (change) {
      for (var i = 0; i < change.change.docs.length; i++) {
        state.emitter.emit(change.direction, change.change.docs[i])
      }
    })

    state.emitter.emit('connect')
  })
}