Updates all jvm metrics to the most recent remote values
517653
public void update(boolean needJvmInfo) {
		if (state == VMInfoState.ERROR_DURING_ATTACH || state == VMInfoState.DETACHED) {
			return;
		}

		try {
			int lastJmxErrorCount = jmxUpdateErrorCount;
			// 将UPDTATE_ERROR重置开始新一轮循环
			state = VMInfoState.ATTACHED;

			// 清空JMX内部缓存
			jmxClient.flush();

			updateUpTime();

			if (needJvmInfo) {
				if (isLinux) {
					updateProcessStatus();
					updateIO();
				}

				updateCpu();
				updateThreads();
				updateClassLoader();
				updateMemoryPool();
				updateGC();
				updateSafepoint();
			}

			// 无新异常，状态重新判定为正常
			if (jmxUpdateErrorCount == lastJmxErrorCount) {
				jmxUpdateErrorCount = 0;
			}
		} catch (Throwable e) {
			// 其他非JMX异常，直接退出
			e.printStackTrace();
			System.out.flush();
			state = VMInfoState.DETACHED;
		}
	}
1285586
def update(gandi, resource, memory, cores, console, password, background,
           reboot):
    
    pwd = None
    if password:
        pwd = click.prompt('password', hide_input=True,
                           confirmation_prompt=True)

    max_memory = None
    if memory:
        max_memory = gandi.iaas.required_max_memory(resource, memory)

    if max_memory and not reboot:
        gandi.echo('memory update must be done offline.')
        if not click.confirm("reboot machine %s?" % resource):
            return

    result = gandi.iaas.update(resource, memory, cores, console, pwd,
                               background, max_memory)
    if background:
        gandi.pretty_echo(result)

    return result
138269
def update():
    '''
    
    '''
    try:
        salt.fileserver.reap_fileserver_cache_dir(
            os.path.join(__opts__['cachedir'], 'roots', 'hash'),
            find_file
        )
    except (IOError, OSError):
        # Hash file won't exist if no files have yet been served up
        pass

    mtime_map_path = os.path.join(__opts__['cachedir'], 'roots', 'mtime_map')
    # data to send on event
    data = {'changed': False,
            'files': {'changed': []},
            'backend': 'roots'}

    # generate the new map
    new_mtime_map = salt.fileserver.generate_mtime_map(__opts__, __opts__['file_roots'])

    old_mtime_map = {}
    # if you have an old map, load that
    if os.path.exists(mtime_map_path):
        with salt.utils.files.fopen(mtime_map_path, 'rb') as fp_:
            for line in fp_:
                line = salt.utils.stringutils.to_unicode(line)
                try:
                    file_path, mtime = line.replace('\n', '').split(':', 1)
                    old_mtime_map[file_path] = mtime
                    if mtime != new_mtime_map.get(file_path, mtime):
                        data['files']['changed'].append(file_path)
                except ValueError:
                    # Document the invalid entry in the log
                    log.warning(
                        'Skipped invalid cache mtime entry in %s: %s',
                        mtime_map_path, line
                    )

    # compare the maps, set changed to the return value
    data['changed'] = salt.fileserver.diff_mtime_map(old_mtime_map, new_mtime_map)

    # compute files that were removed and added
    old_files = set(old_mtime_map.keys())
    new_files = set(new_mtime_map.keys())
    data['files']['removed'] = list(old_files - new_files)
    data['files']['added'] = list(new_files - old_files)

    # write out the new map
    mtime_map_path_dir = os.path.dirname(mtime_map_path)
    if not os.path.exists(mtime_map_path_dir):
        os.makedirs(mtime_map_path_dir)
    with salt.utils.files.fopen(mtime_map_path, 'wb') as fp_:
        for file_path, mtime in six.iteritems(new_mtime_map):
            fp_.write(
                salt.utils.stringutils.to_bytes(
                    '{0}:{1}\n'.format(file_path, mtime)
                )
            )

    if __opts__.get('fileserver_events', False):
        # if there is a change, fire an event
        event = salt.utils.event.get_event(
                'master',
                __opts__['sock_dir'],
                __opts__['transport'],
                opts=__opts__,
                listen=False)
        event.fire_event(data,
                         salt.utils.event.tagify(['roots', 'update'], prefix='fileserver'))
374334
def outdated
      outdateds = []

      latest_specs.each do |local|
        dependency = Gem::Dependency.new local.name, ">= #{local.version}"

        begin
          fetcher = Gem::SpecFetcher.fetcher
          remotes = fetcher.find_matching dependency
          remotes = remotes.map { |(name, version,_),_| version }
        rescue Gem::RemoteFetcher::FetchError => e
          raise unless fetcher.warn_legacy e do
            require 'rubygems/source_info_cache'

            specs = Gem::SourceInfoCache.search_with_source dependency, true

            remotes = specs.map { |spec,| spec.version }
          end
        end

        latest = remotes.sort.last

        outdateds << local.name if latest and local.version < latest
      end

      outdateds
    end
1098815
def _mark_updated(self):
        """"""
        timestamp = datetime.datetime.utcnow().isoformat()
        DB.set_hash_value(self.key, 'updated', timestamp)
5890
def on_epoch_end(self, last_metrics, **kwargs):
        ""
        if not self.nums: return
        metrics = [self.metrics[name]/self.nums for name in self.names]
        return {'last_metrics': last_metrics+metrics}
1274746
private void updateFdMetrics() {
    if (osMbean instanceof com.sun.management.UnixOperatingSystemMXBean) {
      final com.sun.management.UnixOperatingSystemMXBean unix =
          (com.sun.management.UnixOperatingSystemMXBean) osMbean;

      fdCount.setValue(unix.getOpenFileDescriptorCount());
      fdLimit.setValue(unix.getMaxFileDescriptorCount());
    }
  }
618086
def update(self):
        """"""
        # Init new stats
        stats = self.get_init_value()

        # IRQ plugin only available on GNU/Linux
        if not LINUX:
            return self.stats

        if self.input_method == 'local':
            # Grab the stats
            stats = self.irq.get()

        elif self.input_method == 'snmp':
            # not available
            pass

        # Get the TOP 5 (by rate/s)
        stats = sorted(stats,
                       key=operator.itemgetter('irq_rate'),
                       reverse=True)[:5]

        # Update the stats
        self.stats = stats

        return self.stats
1178256
protected void update() {
    //Making more granual locking so that clusterStatus can be fetched from Jobtracker.
    ClusterStatus clusterStatus = taskTrackerManager.getClusterStatus();
    // Recompute locality delay from JobTracker heartbeat interval if enabled.
    // This will also lock the JT, so do it outside of a fair scheduler lock.
    if (autoComputeLocalityDelay) {
      JobTracker jobTracker = (JobTracker) taskTrackerManager;
      localityDelayNodeLocal = Math.min(MAX_AUTOCOMPUTED_LOCALITY_DELAY,
           (long) (1.5 * jobTracker.getNextHeartbeatInterval()));
      localityDelayRackLocal = localityDelayNodeLocal;
    }
    // Got clusterStatus hence acquiring scheduler lock now
    // Remove non-running jobs
    synchronized(this){

      // Reload allocations file if it hasn't been loaded in a while
      if (poolMgr.reloadAllocsIfNecessary()) {
        // Check if the cluster have enough slots for reserving
        poolMgr.checkMinimumSlotsAvailable(clusterStatus, TaskType.MAP);
        poolMgr.checkMinimumSlotsAvailable(clusterStatus, TaskType.REDUCE);
      }

      List<JobInProgress> toRemove = new ArrayList<JobInProgress>();
      for (JobInProgress job: infos.keySet()) {
        int runState = job.getStatus().getRunState();
        if (runState == JobStatus.SUCCEEDED || runState == JobStatus.FAILED
          || runState == JobStatus.KILLED) {
            toRemove.add(job);
        }
      }
      for (JobInProgress job: toRemove) {
        infos.remove(job);
        poolMgr.removeJob(job);
      }
      // Update running jobs with deficits since last update, and compute new
      // slot allocations, weight, shares and task counts
      long now = clock.getTime();
      long timeDelta = now - lastUpdateTime;
      updateDeficits(timeDelta);
      updateRunnability();
      updateTaskCounts();
      updateWeights();
      updateMinAndMaxSlots();
      updateFairShares(clusterStatus);
      if (preemptionEnabled) {
        updatePreemptionVariables();
      }
      sortJobs();
      updatePoolMetrics();
      dumpStatus(now);
      lastUpdateTime = now;
    }
  }
342813
def upgrade():
    """"""
    current_date = datetime.utcnow()

    # Add 'created' and 'updated' columns to RemoteAccount
    _add_created_updated_columns('oauthclient_remoteaccount', current_date)

    # Add 'created' and 'updated' columns to RemoteToken
    _add_created_updated_columns('oauthclient_remotetoken', current_date)

    # Add 'created' and 'updated' columns to UserIdentity
    _add_created_updated_columns('oauthclient_useridentity', current_date)
881228
def update(self):
        """"""
        # Init new stats
        stats = self.get_init_value()

        if self.input_method == 'local':
            # Update stats using the standard system lib
            # Grab MEM using the psutil virtual_memory method
            vm_stats = psutil.virtual_memory()

            # Get all the memory stats (copy/paste of the psutil documentation)
            # total: total physical memory available.
            # available: the actual amount of available memory that can be given instantly to processes that request more memory in bytes; this is calculated by summing different memory values depending on the platform (e.g. free + buffers + cached on Linux) and it is supposed to be used to monitor actual memory usage in a cross platform fashion.
            # percent: the percentage usage calculated as (total - available) / total * 100.
            # used: memory used, calculated differently depending on the platform and designed for informational purposes only.
            # free: memory not being used at all (zeroed) that is readily available; note that this doesn’t reflect the actual memory available (use ‘available’ instead).
            # Platform-specific fields:
            # active: (UNIX): memory currently in use or very recently used, and so it is in RAM.
            # inactive: (UNIX): memory that is marked as not used.
            # buffers: (Linux, BSD): cache for things like file system metadata.
            # cached: (Linux, BSD): cache for various things.
            # wired: (BSD, macOS): memory that is marked to always stay in RAM. It is never moved to disk.
            # shared: (BSD): memory that may be simultaneously accessed by multiple processes.
            self.reset()
            for mem in ['total', 'available', 'percent', 'used', 'free',
                        'active', 'inactive', 'buffers', 'cached',
                        'wired', 'shared']:
                if hasattr(vm_stats, mem):
                    stats[mem] = getattr(vm_stats, mem)

            # Use the 'free'/htop calculation
            # free=available+buffer+cached
            stats['free'] = stats['available']
            if hasattr(stats, 'buffers'):
                stats['free'] += stats['buffers']
            if hasattr(stats, 'cached'):
                stats['free'] += stats['cached']
            # used=total-free
            stats['used'] = stats['total'] - stats['free']
        elif self.input_method == 'snmp':
            # Update stats using SNMP
            if self.short_system_name in ('windows', 'esxi'):
                # Mem stats for Windows|Vmware Esxi are stored in the FS table
                try:
                    fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name],
                                                  bulk=True)
                except KeyError:
                    self.reset()
                else:
                    for fs in fs_stat:
                        # The Physical Memory (Windows) or Real Memory (VMware)
                        # gives statistics on RAM usage and availability.
                        if fs in ('Physical Memory', 'Real Memory'):
                            stats['total'] = int(fs_stat[fs]['size']) * int(fs_stat[fs]['alloc_unit'])
                            stats['used'] = int(fs_stat[fs]['used']) * int(fs_stat[fs]['alloc_unit'])
                            stats['percent'] = float(stats['used'] * 100 / stats['total'])
                            stats['free'] = stats['total'] - stats['used']
                            break
            else:
                # Default behavor for others OS
                stats = self.get_stats_snmp(snmp_oid=snmp_oid['default'])

                if stats['total'] == '':
                    self.reset()
                    return self.stats

                for key in iterkeys(stats):
                    if stats[key] != '':
                        stats[key] = float(stats[key]) * 1024

                # Use the 'free'/htop calculation
                stats['free'] = stats['free'] - stats['total'] + (stats['buffers'] + stats['cached'])

                # used=total-free
                stats['used'] = stats['total'] - stats['free']

                # percent: the percentage usage calculated as (total - available) / total * 100.
                stats['percent'] = float((stats['total'] - stats['free']) / stats['total'] * 100)

        # Update the stats
        self.stats = stats

        return self.stats
590205
def remote():
    """"""
    logger.info("Fetching latest data from PyPI.")
    results = defaultdict(list)
    packages = PackageVersion.objects.exclude(is_editable=True)
    for pv in packages:
        pv.update_from_pypi()
        results[pv.diff_status].append(pv)
        logger.debug("Updated package from PyPI: %r", pv)
    results['refreshed_at'] = tz_now()
    return results
304483
@Override
	protected synchronized void checkDataMaps() throws IOException {
		if (lastUpdateCheck == 0 || lastUpdateCheck < System.currentTimeMillis() - updateInterval) {
			String versionOnServer = getVersionFromServer();
			if (currentVersion == null || versionOnServer.compareTo(currentVersion) > 0) {
				loadDataFromInternet();
				currentVersion = versionOnServer;
			}
			lastUpdateCheck = System.currentTimeMillis();
		}
	}
669911
def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1):
    """"""
    files = command.list_files(*filters, remote_dir=remote_dir)
    most_recent = sorted(files, key=lambda f: f.datetime)
    to_sync = most_recent[-count:]
    _notify_sync(Direction.down, to_sync)
    down_by_files(to_sync[::-1], local_dir=local_dir)
1072215
static void flushToServer(long now) {
        LOG.debug("Flush to BeeInstant Server");
        Collection<String> readyToSubmit = new ArrayList<>();
        metricsQueue.drainTo(readyToSubmit);
        StringBuilder builder = new StringBuilder();
        readyToSubmit.forEach(string -> {
            builder.append(string);
            builder.append("\n");
        });
        if (!readyToSubmit.isEmpty() && beeInstantHost != null) {
            try {
                final String body = builder.toString();
                StringEntity entity = new StringEntity(body);
                entity.setContentType("text/plain");

                String uri = "/PutMetric";
                final String signature = sign(entity);
                if (!signature.isEmpty()) {
                    uri += "?signature=" + URLEncoder.encode(signature, "UTF-8");
                    uri += "&publicKey=" + URLEncoder.encode(publicKey, "UTF-8");
                    uri += "&timestamp=" + now;

                    HttpPost putMetricCommand = new HttpPost(uri);
                    try {
                        putMetricCommand.setEntity(entity);
                        HttpResponse response = httpClient.execute(beeInstantHost, putMetricCommand);
                        LOG.info("Response: " + response.getStatusLine().getStatusCode());
                    } finally {
                        putMetricCommand.releaseConnection();
                    }
                }

            } catch (Throwable e) {
                LOG.error("Fail to emit metrics", e);
            }
        }
    }
1176198
def on_epoch_end(self, last_metrics, **kwargs):
        ""
        return add_metrics(last_metrics, self.val/self.count)
32116
def update(self):
        """"""
        # Init new stats
        stats = self.get_init_value()

        if self.input_method == 'local':
            # Update stats using the standard system lib
            stats = self.glancesgrabhddtemp.get()

        else:
            # Update stats using SNMP
            # Not available for the moment
            pass

        # Update the stats
        self.stats = stats

        return self.stats