VirtualBox

source: vbox/trunk/src/VBox/Main/Performance.cpp@ 27998

Last change on this file since 27998 was 27998, checked in by vboxsync, 15 years ago

Dropped Guest/Pagefile/Usage/Free

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.0 KB
Line 
1/* $Id: Performance.cpp 27998 2010-04-06 11:39:20Z vboxsync $ */
2
3/** @file
4 *
5 * VBox Performance Classes implementation.
6 */
7
8/*
9 * Copyright (C) 2008 Sun Microsystems, Inc.
10 *
11 * This file is part of VirtualBox Open Source Edition (OSE), as
12 * available from http://www.215389.xyz. This file is free software;
13 * you can redistribute it and/or modify it under the terms of the GNU
14 * General Public License (GPL) as published by the Free Software
15 * Foundation, in version 2 as it comes in the "COPYING" file of the
16 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
17 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
18 *
19 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
20 * Clara, CA 95054 USA or visit http://www.sun.com if you need
21 * additional information or have any questions.
22 */
23
24/*
25 * @todo list:
26 *
27 * 1) Detection of erroneous metric names
28 */
29
30#ifndef VBOX_COLLECTOR_TEST_CASE
31#include "VirtualBoxImpl.h"
32#include "MachineImpl.h"
33#endif
34#include "Performance.h"
35
36#include <VBox/com/array.h>
37#include <VBox/com/ptr.h>
38#include <VBox/com/string.h>
39#include <VBox/err.h>
40#include <iprt/string.h>
41#include <iprt/mem.h>
42#include <iprt/cpuset.h>
43
44#include <algorithm>
45
46#include "Logging.h"
47
48using namespace pm;
49
50// Stubs for non-pure virtual methods
51
52int CollectorHAL::getHostCpuLoad(ULONG * /* user */, ULONG * /* kernel */, ULONG * /* idle */)
53{
54 return E_NOTIMPL;
55}
56
57int CollectorHAL::getProcessCpuLoad(RTPROCESS /* process */, ULONG * /* user */, ULONG * /* kernel */)
58{
59 return E_NOTIMPL;
60}
61
62int CollectorHAL::getRawHostCpuLoad(uint64_t * /* user */, uint64_t * /* kernel */, uint64_t * /* idle */)
63{
64 return E_NOTIMPL;
65}
66
67int CollectorHAL::getRawProcessCpuLoad(RTPROCESS /* process */, uint64_t * /* user */, uint64_t * /* kernel */, uint64_t * /* total */)
68{
69 return E_NOTIMPL;
70}
71
72int CollectorHAL::getHostMemoryUsage(ULONG * /* total */, ULONG * /* used */, ULONG * /* available */)
73{
74 return E_NOTIMPL;
75}
76
77int CollectorHAL::getProcessMemoryUsage(RTPROCESS /* process */, ULONG * /* used */)
78{
79 return E_NOTIMPL;
80}
81
82int CollectorHAL::enable()
83{
84 return E_NOTIMPL;
85}
86
87int CollectorHAL::disable()
88{
89 return E_NOTIMPL;
90}
91
92/* Generic implementations */
93
94int CollectorHAL::getHostCpuMHz(ULONG *mhz)
95{
96 unsigned cCpus = 0;
97 uint64_t u64TotalMHz = 0;
98 RTCPUSET OnlineSet;
99 RTMpGetOnlineSet(&OnlineSet);
100 for (RTCPUID iCpu = 0; iCpu < RTCPUSET_MAX_CPUS; iCpu++)
101 {
102 LogAleksey(("{%p} " LOG_FN_FMT ": Checking if CPU %d is member of online set...\n",
103 this, __PRETTY_FUNCTION__, (int)iCpu));
104 if (RTCpuSetIsMemberByIndex(&OnlineSet, iCpu))
105 {
106 LogAleksey(("{%p} " LOG_FN_FMT ": Getting frequency for CPU %d...\n",
107 this, __PRETTY_FUNCTION__, (int)iCpu));
108 uint32_t uMHz = RTMpGetCurFrequency(RTMpCpuIdFromSetIndex(iCpu));
109 if (uMHz != 0)
110 {
111 LogAleksey(("{%p} " LOG_FN_FMT ": CPU %d %u MHz\n",
112 this, __PRETTY_FUNCTION__, (int)iCpu, uMHz));
113 u64TotalMHz += uMHz;
114 cCpus++;
115 }
116 }
117 }
118
119 AssertReturn(cCpus, VERR_NOT_IMPLEMENTED);
120 *mhz = (ULONG)(u64TotalMHz / cCpus);
121
122 return VINF_SUCCESS;
123}
124
125#ifndef VBOX_COLLECTOR_TEST_CASE
126CollectorGuestHAL::~CollectorGuestHAL()
127{
128 Assert(!cEnabled);
129}
130
131int CollectorGuestHAL::enable()
132{
133 HRESULT ret = S_OK;
134
135 if (ASMAtomicIncU32(&cEnabled) == 1)
136 {
137 ComPtr<IInternalSessionControl> directControl;
138
139 ret = mMachine->getDirectControl(&directControl);
140 if (ret != S_OK)
141 return ret;
142
143 /* get the associated console; this is a remote call (!) */
144 ret = directControl->GetRemoteConsole(mConsole.asOutParam());
145 if (ret != S_OK)
146 return ret;
147
148 ret = mConsole->COMGETTER(Guest)(mGuest.asOutParam());
149 if (ret == S_OK)
150 mGuest->COMSETTER(StatisticsUpdateInterval)(1 /* 1 sec */);
151 }
152 return ret;
153}
154
155int CollectorGuestHAL::disable()
156{
157 if (ASMAtomicDecU32(&cEnabled) == 0)
158 {
159 Assert(mGuest && mConsole);
160 mGuest->COMSETTER(StatisticsUpdateInterval)(0 /* off */);
161 }
162 return S_OK;
163}
164
165int CollectorGuestHAL::preCollect(const CollectorHints& hints, uint64_t iTick)
166{
167 if ( mGuest
168 && iTick != mLastTick)
169 {
170 mGuest->InternalGetStatistics(0, &mCpuUser, &mCpuKernel, &mCpuIdle,
171 &mMemTotal, &mMemFree, &mMemBalloon, &mMemCache,
172 &mPageTotal);
173 mLastTick = iTick;
174 }
175 return S_OK;
176}
177
178#endif /* VBOX_COLLECTOR_TEST_CASE */
179
180bool BaseMetric::collectorBeat(uint64_t nowAt)
181{
182 if (isEnabled())
183 {
184 if (nowAt - mLastSampleTaken >= mPeriod * 1000)
185 {
186 mLastSampleTaken = nowAt;
187 Log4(("{%p} " LOG_FN_FMT ": Collecting %s for obj(%p)...\n",
188 this, __PRETTY_FUNCTION__, getName(), (void *)mObject));
189 return true;
190 }
191 }
192 return false;
193}
194
195/*bool BaseMetric::associatedWith(ComPtr<IUnknown> object)
196{
197 LogFlowThisFunc(("mObject(%p) == object(%p) is %s.\n", mObject, object, mObject == object ? "true" : "false"));
198 return mObject == object;
199}*/
200
201void HostCpuLoad::init(ULONG period, ULONG length)
202{
203 mPeriod = period;
204 mLength = length;
205 mUser->init(mLength);
206 mKernel->init(mLength);
207 mIdle->init(mLength);
208}
209
210void HostCpuLoad::collect()
211{
212 ULONG user, kernel, idle;
213 int rc = mHAL->getHostCpuLoad(&user, &kernel, &idle);
214 if (RT_SUCCESS(rc))
215 {
216 mUser->put(user);
217 mKernel->put(kernel);
218 mIdle->put(idle);
219 }
220}
221
222void HostCpuLoadRaw::preCollect(CollectorHints& hints, uint64_t iTick)
223{
224 hints.collectHostCpuLoad();
225}
226
227void HostCpuLoadRaw::collect()
228{
229 uint64_t user, kernel, idle;
230 uint64_t userDiff, kernelDiff, idleDiff, totalDiff;
231
232 int rc = mHAL->getRawHostCpuLoad(&user, &kernel, &idle);
233 if (RT_SUCCESS(rc))
234 {
235 userDiff = user - mUserPrev;
236 kernelDiff = kernel - mKernelPrev;
237 idleDiff = idle - mIdlePrev;
238 totalDiff = userDiff + kernelDiff + idleDiff;
239
240 if (totalDiff == 0)
241 {
242 /* This is only possible if none of counters has changed! */
243 LogFlowThisFunc(("Impossible! User, kernel and idle raw "
244 "counters has not changed since last sample.\n" ));
245 mUser->put(0);
246 mKernel->put(0);
247 mIdle->put(0);
248 }
249 else
250 {
251 mUser->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * userDiff / totalDiff));
252 mKernel->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * kernelDiff / totalDiff));
253 mIdle->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * idleDiff / totalDiff));
254 }
255
256 mUserPrev = user;
257 mKernelPrev = kernel;
258 mIdlePrev = idle;
259 }
260}
261
262void HostCpuMhz::init(ULONG period, ULONG length)
263{
264 mPeriod = period;
265 mLength = length;
266 mMHz->init(mLength);
267}
268
269void HostCpuMhz::collect()
270{
271 ULONG mhz;
272 int rc = mHAL->getHostCpuMHz(&mhz);
273 if (RT_SUCCESS(rc))
274 mMHz->put(mhz);
275}
276
277void HostRamUsage::init(ULONG period, ULONG length)
278{
279 mPeriod = period;
280 mLength = length;
281 mTotal->init(mLength);
282 mUsed->init(mLength);
283 mAvailable->init(mLength);
284}
285
286void HostRamUsage::preCollect(CollectorHints& hints, uint64_t iTick)
287{
288 hints.collectHostRamUsage();
289}
290
291void HostRamUsage::collect()
292{
293 ULONG total, used, available;
294 int rc = mHAL->getHostMemoryUsage(&total, &used, &available);
295 if (RT_SUCCESS(rc))
296 {
297 mTotal->put(total);
298 mUsed->put(used);
299 mAvailable->put(available);
300 }
301}
302
303
304
305void MachineCpuLoad::init(ULONG period, ULONG length)
306{
307 mPeriod = period;
308 mLength = length;
309 mUser->init(mLength);
310 mKernel->init(mLength);
311}
312
313void MachineCpuLoad::collect()
314{
315 ULONG user, kernel;
316 int rc = mHAL->getProcessCpuLoad(mProcess, &user, &kernel);
317 if (RT_SUCCESS(rc))
318 {
319 mUser->put(user);
320 mKernel->put(kernel);
321 }
322}
323
324void MachineCpuLoadRaw::preCollect(CollectorHints& hints, uint64_t iTick)
325{
326 hints.collectProcessCpuLoad(mProcess);
327}
328
329void MachineCpuLoadRaw::collect()
330{
331 uint64_t processUser, processKernel, hostTotal;
332
333 int rc = mHAL->getRawProcessCpuLoad(mProcess, &processUser, &processKernel, &hostTotal);
334 if (RT_SUCCESS(rc))
335 {
336 if (hostTotal == mHostTotalPrev)
337 {
338 /* Nearly impossible, but... */
339 mUser->put(0);
340 mKernel->put(0);
341 }
342 else
343 {
344 mUser->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * (processUser - mProcessUserPrev) / (hostTotal - mHostTotalPrev)));
345 mKernel->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * (processKernel - mProcessKernelPrev ) / (hostTotal - mHostTotalPrev)));
346 }
347
348 mHostTotalPrev = hostTotal;
349 mProcessUserPrev = processUser;
350 mProcessKernelPrev = processKernel;
351 }
352}
353
354void MachineRamUsage::init(ULONG period, ULONG length)
355{
356 mPeriod = period;
357 mLength = length;
358 mUsed->init(mLength);
359}
360
361void MachineRamUsage::preCollect(CollectorHints& hints, uint64_t iTick)
362{
363 hints.collectProcessRamUsage(mProcess);
364}
365
366void MachineRamUsage::collect()
367{
368 ULONG used;
369 int rc = mHAL->getProcessMemoryUsage(mProcess, &used);
370 if (RT_SUCCESS(rc))
371 mUsed->put(used);
372}
373
374
375void GuestCpuLoad::init(ULONG period, ULONG length)
376{
377 mPeriod = period;
378 mLength = length;
379
380 mUser->init(mLength);
381 mKernel->init(mLength);
382 mIdle->init(mLength);
383}
384
385void GuestCpuLoad::preCollect(CollectorHints& hints, uint64_t iTick)
386{
387 mHAL->preCollect(hints, iTick);
388}
389
390void GuestCpuLoad::collect()
391{
392 ULONG CpuUser = 0, CpuKernel = 0, CpuIdle = 0;
393
394 mGuestHAL->getGuestCpuLoad(&CpuUser, &CpuKernel, &CpuIdle);
395 mUser->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * CpuUser) / 100);
396 mKernel->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * CpuKernel) / 100);
397 mIdle->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * CpuIdle) / 100);
398}
399
400void GuestRamUsage::init(ULONG period, ULONG length)
401{
402 mPeriod = period;
403 mLength = length;
404
405 mTotal->init(mLength);
406 mFree->init(mLength);
407 mBallooned->init(mLength);
408 mCache->init(mLength);
409 mPagedTotal->init(mLength);
410}
411
412void GuestRamUsage::preCollect(CollectorHints& hints, uint64_t iTick)
413{
414 mHAL->preCollect(hints, iTick);
415}
416
417void GuestRamUsage::collect()
418{
419 ULONG ulMemTotal = 0, ulMemFree = 0, ulMemBalloon = 0, ulMemCache = 0, ulPageTotal = 0;
420
421 mGuestHAL->getGuestMemLoad(&ulMemTotal, &ulMemFree, &ulMemBalloon, &ulMemCache, &ulPageTotal);
422 mTotal->put(ulMemTotal);
423 mFree->put(ulMemFree);
424 mBallooned->put(ulMemBalloon);
425 mCache->put(ulMemCache);
426 mPagedTotal->put(ulPageTotal);
427}
428
429void CircularBuffer::init(ULONG ulLength)
430{
431 if (mData)
432 RTMemFree(mData);
433 mLength = ulLength;
434 if (mLength)
435 mData = (ULONG*)RTMemAllocZ(ulLength * sizeof(ULONG));
436 else
437 mData = NULL;
438 mWrapped = false;
439 mEnd = 0;
440 mSequenceNumber = 0;
441}
442
443ULONG CircularBuffer::length()
444{
445 return mWrapped ? mLength : mEnd;
446}
447
448void CircularBuffer::put(ULONG value)
449{
450 if (mData)
451 {
452 mData[mEnd++] = value;
453 if (mEnd >= mLength)
454 {
455 mEnd = 0;
456 mWrapped = true;
457 }
458 ++mSequenceNumber;
459 }
460}
461
462void CircularBuffer::copyTo(ULONG *data)
463{
464 if (mWrapped)
465 {
466 memcpy(data, mData + mEnd, (mLength - mEnd) * sizeof(ULONG));
467 // Copy the wrapped part
468 if (mEnd)
469 memcpy(data + (mLength - mEnd), mData, mEnd * sizeof(ULONG));
470 }
471 else
472 memcpy(data, mData, mEnd * sizeof(ULONG));
473}
474
475void SubMetric::query(ULONG *data)
476{
477 copyTo(data);
478}
479
480void Metric::query(ULONG **data, ULONG *count, ULONG *sequenceNumber)
481{
482 ULONG length;
483 ULONG *tmpData;
484
485 length = mSubMetric->length();
486 *sequenceNumber = mSubMetric->getSequenceNumber() - length;
487 if (length)
488 {
489 tmpData = (ULONG*)RTMemAlloc(sizeof(*tmpData)*length);
490 mSubMetric->query(tmpData);
491 if (mAggregate)
492 {
493 *count = 1;
494 *data = (ULONG*)RTMemAlloc(sizeof(**data));
495 **data = mAggregate->compute(tmpData, length);
496 RTMemFree(tmpData);
497 }
498 else
499 {
500 *count = length;
501 *data = tmpData;
502 }
503 }
504 else
505 {
506 *count = 0;
507 *data = 0;
508 }
509}
510
511ULONG AggregateAvg::compute(ULONG *data, ULONG length)
512{
513 uint64_t tmp = 0;
514 for (ULONG i = 0; i < length; ++i)
515 tmp += data[i];
516 return (ULONG)(tmp / length);
517}
518
519const char * AggregateAvg::getName()
520{
521 return "avg";
522}
523
524ULONG AggregateMin::compute(ULONG *data, ULONG length)
525{
526 ULONG tmp = *data;
527 for (ULONG i = 0; i < length; ++i)
528 if (data[i] < tmp)
529 tmp = data[i];
530 return tmp;
531}
532
533const char * AggregateMin::getName()
534{
535 return "min";
536}
537
538ULONG AggregateMax::compute(ULONG *data, ULONG length)
539{
540 ULONG tmp = *data;
541 for (ULONG i = 0; i < length; ++i)
542 if (data[i] > tmp)
543 tmp = data[i];
544 return tmp;
545}
546
547const char * AggregateMax::getName()
548{
549 return "max";
550}
551
552Filter::Filter(ComSafeArrayIn(IN_BSTR, metricNames),
553 ComSafeArrayIn(IUnknown *, objects))
554{
555 /*
556 * Let's work around null/empty safe array mess. I am not sure there is
557 * a way to pass null arrays via webservice, I haven't found one. So I
558 * guess the users will be forced to use empty arrays instead. Constructing
559 * an empty SafeArray is a bit awkward, so what we do in this method is
560 * actually convert null arrays to empty arrays and pass them down to
561 * init() method. If someone knows how to do it better, please be my guest,
562 * fix it.
563 */
564 if (ComSafeArrayInIsNull(metricNames))
565 {
566 com::SafeArray<BSTR> nameArray;
567 if (ComSafeArrayInIsNull(objects))
568 {
569 com::SafeIfaceArray<IUnknown> objectArray;
570 objectArray.reset(0);
571 init(ComSafeArrayAsInParam(nameArray),
572 ComSafeArrayAsInParam(objectArray));
573 }
574 else
575 {
576 com::SafeIfaceArray<IUnknown> objectArray(ComSafeArrayInArg(objects));
577 init(ComSafeArrayAsInParam(nameArray),
578 ComSafeArrayAsInParam(objectArray));
579 }
580 }
581 else
582 {
583 com::SafeArray<IN_BSTR> nameArray(ComSafeArrayInArg(metricNames));
584 if (ComSafeArrayInIsNull(objects))
585 {
586 com::SafeIfaceArray<IUnknown> objectArray;
587 objectArray.reset(0);
588 init(ComSafeArrayAsInParam(nameArray),
589 ComSafeArrayAsInParam(objectArray));
590 }
591 else
592 {
593 com::SafeIfaceArray<IUnknown> objectArray(ComSafeArrayInArg(objects));
594 init(ComSafeArrayAsInParam(nameArray),
595 ComSafeArrayAsInParam(objectArray));
596 }
597 }
598}
599
600void Filter::init(ComSafeArrayIn(IN_BSTR, metricNames),
601 ComSafeArrayIn(IUnknown *, objects))
602{
603 com::SafeArray<IN_BSTR> nameArray(ComSafeArrayInArg(metricNames));
604 com::SafeIfaceArray<IUnknown> objectArray(ComSafeArrayInArg(objects));
605
606 if (!objectArray.size())
607 {
608 if (nameArray.size())
609 {
610 for (size_t i = 0; i < nameArray.size(); ++i)
611 processMetricList(com::Utf8Str(nameArray[i]), ComPtr<IUnknown>());
612 }
613 else
614 processMetricList("*", ComPtr<IUnknown>());
615 }
616 else
617 {
618 for (size_t i = 0; i < objectArray.size(); ++i)
619 switch (nameArray.size())
620 {
621 case 0:
622 processMetricList("*", objectArray[i]);
623 break;
624 case 1:
625 processMetricList(com::Utf8Str(nameArray[0]), objectArray[i]);
626 break;
627 default:
628 processMetricList(com::Utf8Str(nameArray[i]), objectArray[i]);
629 break;
630 }
631 }
632}
633
634void Filter::processMetricList(const com::Utf8Str &name, const ComPtr<IUnknown> object)
635{
636 size_t startPos = 0;
637
638 for (size_t pos = name.find(",");
639 pos != com::Utf8Str::npos;
640 pos = name.find(",", startPos))
641 {
642 mElements.push_back(std::make_pair(object, iprt::MiniString(name.substr(startPos, pos - startPos).c_str())));
643 startPos = pos + 1;
644 }
645 mElements.push_back(std::make_pair(object, iprt::MiniString(name.substr(startPos).c_str())));
646}
647
648/**
649 * The following method was borrowed from stamR3Match (VMM/STAM.cpp) and
650 * modified to handle the special case of trailing colon in the pattern.
651 *
652 * @returns True if matches, false if not.
653 * @param pszPat Pattern.
654 * @param pszName Name to match against the pattern.
655 * @param fSeenColon Seen colon (':').
656 */
657bool Filter::patternMatch(const char *pszPat, const char *pszName,
658 bool fSeenColon)
659{
660 /* ASSUMES ASCII */
661 for (;;)
662 {
663 char chPat = *pszPat;
664 switch (chPat)
665 {
666 default:
667 if (*pszName != chPat)
668 return false;
669 break;
670
671 case '*':
672 {
673 while ((chPat = *++pszPat) == '*' || chPat == '?')
674 /* nothing */;
675
676 /* Handle a special case, the mask terminating with a colon. */
677 if (chPat == ':')
678 {
679 if (!fSeenColon && !pszPat[1])
680 return !strchr(pszName, ':');
681 fSeenColon = true;
682 }
683
684 for (;;)
685 {
686 char ch = *pszName++;
687 if ( ch == chPat
688 && ( !chPat
689 || patternMatch(pszPat + 1, pszName, fSeenColon)))
690 return true;
691 if (!ch)
692 return false;
693 }
694 /* won't ever get here */
695 break;
696 }
697
698 case '?':
699 if (!*pszName)
700 return false;
701 break;
702
703 /* Handle a special case, the mask terminating with a colon. */
704 case ':':
705 if (!fSeenColon && !pszPat[1])
706 return !*pszName;
707 if (*pszName != ':')
708 return false;
709 fSeenColon = true;
710 break;
711
712 case '\0':
713 return !*pszName;
714 }
715 pszName++;
716 pszPat++;
717 }
718 return true;
719}
720
721bool Filter::match(const ComPtr<IUnknown> object, const iprt::MiniString &name) const
722{
723 ElementList::const_iterator it;
724
725 LogAleksey(("Filter::match(%p, %s)\n", static_cast<const IUnknown*> (object), name.c_str()));
726 for (it = mElements.begin(); it != mElements.end(); it++)
727 {
728 LogAleksey(("...matching against(%p, %s)\n", static_cast<const IUnknown*> ((*it).first), (*it).second.c_str()));
729 if ((*it).first.isNull() || (*it).first == object)
730 {
731 // Objects match, compare names
732 if (patternMatch((*it).second.c_str(), name.c_str()))
733 {
734 LogFlowThisFunc(("...found!\n"));
735 return true;
736 }
737 }
738 }
739 LogAleksey(("...no matches!\n"));
740 return false;
741}
742/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette