Sync local instance against a single remote object

    :param * org: the org
    :param * syncer: the local model syncer
    :param * remote: the remote object
    :return: the outcome (created, updated or deleted)
771692
def sync_from_remote(org, syncer, remote):
    
    identity = syncer.identify_remote(remote)

    with syncer.lock(org, identity):
        existing = syncer.fetch_local(org, identity)

        # derive kwargs for the local model (none return here means don't keep)
        remote_as_kwargs = syncer.local_kwargs(org, remote)

        # exists locally
        if existing:
            existing.org = org  # saves pre-fetching since we already have the org

            if remote_as_kwargs:
                if syncer.update_required(existing, remote, remote_as_kwargs) or not existing.is_active:
                    for field, value in remote_as_kwargs.items():
                        setattr(existing, field, value)

                    existing.is_active = True
                    existing.save()
                    return SyncOutcome.updated

            elif existing.is_active:  # exists locally, but shouldn't now to due to model changes
                syncer.delete_local(existing)
                return SyncOutcome.deleted

        elif remote_as_kwargs:
            syncer.model.objects.create(**remote_as_kwargs)
            return SyncOutcome.created

    return SyncOutcome.ignored
104131
def sync_path_to_host(path, host, user, verbose=False, cmd=None, gid=None,
                      fatal=False):
    
    cmd = cmd or copy(BASE_CMD)
    if not verbose:
        cmd.append('-silent')

    # removing trailing slash from directory paths, unison
    # doesn't like these.
    if path.endswith('/'):
        path = path[:(len(path) - 1)]

    cmd = cmd + [path, 'ssh://%s@%s/%s' % (user, host, path)]

    try:
        log('Syncing local path %s to %s@%s:%s' % (path, user, host, path))
        run_as_user(user, cmd, gid)
    except Exception:
        log('Error syncing remote files')
        if fatal:
            raise
415330
private Future<M> sync() {
        logger.debug("Synchronization of Remote[" + this + "] triggered...");
        try {
            validateInitialization();
            try {
                SyncTaskCallable syncCallable = new SyncTaskCallable();

                final Future<M> currentSyncTask = GlobalCachedExecutorService.submit(syncCallable);
                syncCallable.setRelatedFuture(currentSyncTask);
                return currentSyncTask;
            } catch (java.util.concurrent.RejectedExecutionException | NullPointerException ex) {
                throw new CouldNotPerformException("Could not request the current status.", ex);
            }
        } catch (CouldNotPerformException ex) {
            return FutureProcessor.canceledFuture(ex);
        }
    }
596262
def _sync_repo(self, repo_url: str, revision: str or None = None) -> Path:
        '''
        '''

        repo_name = repo_url.split('/')[-1].rsplit('.', maxsplit=1)[0]
        repo_path = (self._cache_path / repo_name).resolve()

        self.logger.debug(f'Synchronizing with repo; URL: {repo_url}, revision: {revision}')

        try:
            self.logger.debug(f'Cloning repo {repo_url} to {repo_path}')

            run(
                f'git clone {repo_url} {repo_path}',
                shell=True,
                check=True,
                stdout=PIPE,
                stderr=STDOUT
            )

        except CalledProcessError as exception:
            if repo_path.exists():
                self.logger.debug('Repo already cloned; pulling from remote')

                try:
                    run(
                        'git pull',
                        cwd=repo_path,
                        shell=True,
                        check=True,
                        stdout=PIPE,
                        stderr=STDOUT
                    )

                except CalledProcessError as exception:
                    self.logger.warning(str(exception))

            else:
                self.logger.error(str(exception))

        if revision:
            run(
                f'git checkout {revision}',
                cwd=repo_path,
                shell=True,
                check=True,
                stdout=PIPE,
                stderr=STDOUT
            )

        return repo_path
1265823
def sync(self):
        
        LOGGER.debug("Application.sync")
        params = None
        if self.id is not None:
            params = {'id': self.id}
        elif self.name is not None:
            params = {'name': self.name}

        if params is not None:
            args = {'http_operation': 'GET', 'operation_path': 'get', 'parameters': params}
            response = ApplicationService.requester.call(args)
            if response.rc != 0:
                LOGGER.warning(
                    'Application.sync - Problem while syncing application (name:' + self.name + 'id: ' + str(self.id) +
                    '). Reason: ' + str(response.response_content) + '-' + str(response.error_message) +
                    " (" + str(response.rc) + ")"
                )
            else:
                json_obj = response.response_content
                self.id = json_obj['applicationID']
                self.name = json_obj['applicationName']
                self.description = json_obj['applicationDescription']
                self.short_name = json_obj['applicationShortName']
                self.color_code = json_obj['applicationColorCode']
                if json_obj['applicationCompanyID'] == -1:
                    self.company_id = None
                else:
                    self.company_id = json_obj['applicationCompanyID']
                if json_obj['applicationTeamID'] == -1:
                    self.team_id = None
                else:
                    self.team_id = json_obj['applicationTeamID']
                self.osi_ids = json_obj['applicationOSInstancesID']
1159805
def replicate(self, doc_id, source, target, continuous=False):
        
        if doc_id in self["_replicator"]:
            return
        data = {
            "_id": doc_id,
            "source": source,
            "target": target,
            "continuous": continuous
        }
        self["_replicator"][doc_id] = data
1348850
def sync(source,
         destination,
         host,
         user=None,
         sudo=False,
         run_as=None,
         options=('-rltvz', '--no-perms', '--no-group'),
         excludes=(),
         exclude_from=None,
         delete=False,
         dry_run=False,
         mode='u=rwX,g=rwX,o=',
         quiet=True,
         pull=False,
         # Args passed through to local command:
         stdout: arg(type=StreamOptions) = None,
         stderr: arg(type=StreamOptions) = None,
         echo=False,
         raise_on_error=True,
         ) -> Result:
    
    source = abs_path(source, keep_slash=True)
    destination = abs_path(destination, keep_slash=True)
    connection_str = '{user}@{host}'.format_map(locals()) if user else host
    push = not pull

    if sudo:
        rsync_path = ('--rsync-path', 'sudo rsync')
    elif run_as:
        rsync_path = ('--rsync-path', 'sudo -u {run_as} rsync'.format_map(locals()))
    else:
        rsync_path = None

    if push:
        destination = '{connection_str}:{destination}'.format_map(locals())
    else:
        source = '{connection_str}:{source}'.format_map(locals())

    args = (
        'rsync',
        rsync_path,
        options,
        ('--chmod', mode) if mode else None,
        tuple(('--exclude', exclude) for exclude in excludes),
        ('--exclude-from', exclude_from) if exclude_from else None,
        '--delete' if delete else None,
        '--dry-run' if dry_run else None,
        '--quiet' if quiet else None,
        source,
        destination,
    )
    return local(args, stdout=stdout, stderr=stderr, echo=echo, raise_on_error=raise_on_error)
1235596
def sync_local_to_remote(force="no"):
    

    _check_requirements()

    if force != "yes":
        message = "This will replace the remote database '%s' with your "\
            "local '%s', are you sure [y/n]" % (env.psql_db, env.local_psql_db)
        answer = prompt(message, "y")

        if answer != "y":
            logger.info("Sync stopped")
            return

    init_tasks()  # Bootstrap fabrik

    # Create database dump
    local_file = "sync_%s.sql.tar.gz" % int(time.time()*1000)
    local_path = "/tmp/%s" % local_file

    with context_managers.shell_env(PGPASSWORD=env.local_psql_password):
        elocal("pg_dump -h localhost -Fc -f %s -U %s %s -x -O" % (
            local_path, env.local_psql_user, env.local_psql_db
        ))

    remote_path = "/tmp/%s" % local_file

    # Upload sync file
    put(remote_path, local_path)

    # Import sync file by performing the following task (drop, create, import)
    with context_managers.shell_env(PGPASSWORD=env.psql_password):
        env.run("pg_restore --clean -h localhost -d %s -U %s '%s'" % (
            env.psql_db,
            env.psql_user,
            remote_path)
        )

    # Cleanup
    env.run("rm %s" % remote_path)
    elocal("rm %s" % local_path)

    # Trigger hook
    run_hook("postgres.after_sync_local_to_remote")

    logger.info("Sync complete")
1022411
def sync_all(name, **kwargs):
    '''
    
    '''
    ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}

    if __opts__['test']:
        ret['result'] = None
        ret['comment'] = "saltutil.sync_all would have been run"
        return ret

    try:
        sync_status = __salt__['saltutil.sync_all'](**kwargs)
        for key, value in sync_status.items():
            if value:
                ret['changes'][key] = value
                ret['comment'] = "Sync performed"
    except Exception as e:
        log.error("Failed to run saltutil.sync_all: %s", e)
        ret['result'] = False
        ret['comment'] = "Failed to run sync_all: {0}".format(e)
        return ret

    if not ret['changes']:
        ret['comment'] = "No updates to sync"

    return ret
1264593
def sync(
    ctx,
    state,
    bare=False,
    user=False,
    unused=False,
    **kwargs
):
    """"""
    from ..core import do_sync

    retcode = do_sync(
        ctx=ctx,
        dev=state.installstate.dev,
        three=state.three,
        python=state.python,
        bare=bare,
        dont_upgrade=(not state.installstate.keep_outdated),
        user=user,
        clear=state.clear,
        unused=unused,
        sequential=state.installstate.sequential,
        pypi_mirror=state.pypi_mirror,
    )
    if retcode:
        ctx.abort()
1372159
def sync(context, provider, **kwargs):  # pylint: disable=too-many-locals
    """"""
    session = get_session(provider.region)
    bucket_name = OutputLookup.handle(kwargs.get('bucket_output_lookup'),
                                      provider=provider,
                                      context=context)

    if context.hook_data['staticsite']['deploy_is_current']:
        LOGGER.info('staticsite: skipping upload; latest version already '
                    'deployed')
    else:
        distribution_id = OutputLookup.handle(
            kwargs.get('distributionid_output_lookup'),
            provider=provider,
            context=context
        )
        distribution_domain = OutputLookup.handle(
            kwargs.get('distributiondomain_output_lookup'),
            provider=provider,
            context=context
        )

        # Using the awscli for s3 syncing is incredibly suboptimal, but on
        # balance it's probably the most stable/efficient option for syncing
        # the files until https://github.com/boto/boto3/issues/358 is resolved
        aws_cli(['s3',
                 'sync',
                 context.hook_data['staticsite']['app_directory'],
                 "s3://%s/" % bucket_name,
                 '--delete'])

        cf_client = session.client('cloudfront')
        cf_client.create_invalidation(
            DistributionId=distribution_id,
            InvalidationBatch={'Paths': {'Quantity': 1, 'Items': ['/*']},
                               'CallerReference': str(time.time())}
        )
        LOGGER.info("staticsite: sync & CF invalidation of %s (domain %s) "
                    "complete",
                    distribution_id,
                    distribution_domain)

        if not context.hook_data['staticsite'].get('hash_tracking_disabled'):
            LOGGER.info("staticsite: updating environment SSM parameter %s "
                        "with hash %s",
                        context.hook_data['staticsite']['hash_tracking_parameter'],  # noqa
                        context.hook_data['staticsite']['hash'])
            ssm_client = session.client('ssm')
            ssm_client.put_parameter(
                Name=context.hook_data['staticsite']['hash_tracking_parameter'],  # noqa
                Description='Hash of currently deployed static website source',
                Value=context.hook_data['staticsite']['hash'],
                Type='String',
                Overwrite=True
            )
    LOGGER.info("staticsite: cleaning up old site archives...")
    archives = []
    s3_client = session.client('s3')
    list_objects_v2_paginator = s3_client.get_paginator('list_objects_v2')
    response_iterator = list_objects_v2_paginator.paginate(
        Bucket=context.hook_data['staticsite']['artifact_bucket_name'],
        Prefix=context.hook_data['staticsite']['artifact_key_prefix']
    )
    for page in response_iterator:
        archives.extend(page.get('Contents', []))
    archives_to_prune = get_archives_to_prune(
        archives,
        context.hook_data['staticsite']
    )
    # Iterate in chunks of 1000 to match delete_objects limit
    for objects in [archives_to_prune[i:i + 1000]
                    for i in range(0, len(archives_to_prune), 1000)]:
        s3_client.delete_objects(
            Bucket=context.hook_data['staticsite']['artifact_bucket_name'],
            Delete={'Objects': [{'Key': i} for i in objects]}
        )
    return True
609055
def sync(self, json_obj=None):
        
        LOGGER.debug("Transport.sync")
        if json_obj is None:
            params = None
            if self.id is not None:
                params = SessionService.complete_transactional_req({'ID': self.id})

            if params is not None:
                if MappingService.driver_type != DriverFactory.DRIVER_REST:
                    params['OPERATION'] = 'getTransport'
                    args = {'properties': params}
                else:
                    args = {'http_operation': 'GET', 'operation_path': 'get', 'parameters': params}

                response = TransportService.requester.call(args)

                if MappingService.driver_type != DriverFactory.DRIVER_REST:
                    response = response.get()

                if response.rc == 0:
                    json_obj = response.response_content
                else:
                    err_msg = 'Transport.sync - Problem while syncing transport (id: ' + str(self.id) + '). ' \
                              'Reason: ' + str(response.response_content) + ' - ' + str(response.error_message) + \
                              " (" + str(response.rc) + ")"
                    LOGGER.warning(err_msg)
                    if response.rc == 500 and ArianeMappingOverloadError.ERROR_MSG in response.error_message:
                        raise ArianeMappingOverloadError("Transport.sync",
                                                         ArianeMappingOverloadError.ERROR_MSG)
                    # traceback.print_stack()
        elif 'transportID' not in json_obj:
            err_msg = 'Transport.sync - Problem while syncing transport (id: ' + str(self.id) + '). ' \
                      'Reason: inconsistent json_obj' + str(json_obj) + " from : \n"
            LOGGER.warning(err_msg)
            # traceback.print_stack()

        if json_obj is not None:
            self.id = json_obj['transportID']
            self.name = json_obj['transportName']
            if MappingService.driver_type != DriverFactory.DRIVER_REST:
                if 'transportProperties' in json_obj:
                    self.properties = DriverTools.json2properties(json_obj['transportProperties'])
                else:
                    self.properties = None
            else:
                self.properties = json_obj['transportProperties'] if 'transportProperties' in json_obj else None
740321
def sync(self, bForce):
        """"""

        fn = self.function_table.sync
        peError = EVRSettingsError()
        result = fn(bForce, byref(peError))
        return result, peError
769709
def synchronizer(self):
        
        if not self.synchronizer_path or self.synchronizer_path == 'None' or not self.layer:
            return False
        # ensure data is up to date
        if (self._synchronizer is not None and self._synchronizer_class.__name__ not in self.synchronizer_path):
            self._synchronizer = None
            self._synchronizer_class = None
        # init synchronizer only if necessary
        if not self._synchronizer:
            self._synchronizer = (self.synchronizer_class)(self.layer)
        return self._synchronizer
1138056
def sync(self):
        ''''''
        if self.flag == 'r':
            return
        filename = self.filename
        tempname = filename + '.tmp'
        fileobj = open(tempname, 'wb' if self.file_format == 'pickle' else 'w')
        try:
            self.dump(fileobj)
        except Exception:
            os.remove(tempname)
            raise
        finally:
            fileobj.close()
        shutil.move(tempname, self.filename)    # atomic commit
        if self.mode is not None:
            os.chmod(self.filename, self.mode)
726197
def _get_sync(self, url):
        
        response = self.session.get(url)
        if response.status_code == requests.codes.ok:
            return response.json()
        else:
            raise HTTPError
876411
def sync_with(name, syncer_id = nil, &block)
      @syncers << get_class_from_scope(Syncer, name).new(syncer_id, &block)
    end