-
Notifications
You must be signed in to change notification settings - Fork 270
/
Copy pathgcbase.cpp
4432 lines (3745 loc) · 151 KB
/
gcbase.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "stdafx.h"
#include "gcbase.h"
#include "tier1/interface.h"
#include "tier0/minidump.h"
#include "tier0/icommandline.h"
#include "gcjob.h"
#include "sqlaccess/schemaupdate.h"
#include "gcsystemmsgs.h"
#include "rtime.h"
#include "msgprotobuf.h"
#include "gcsdk_gcmessages.pb.h"
#include "gcsdk/gcparalleljobfarm.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
namespace GCSDK
{
//----------------------------------------------------------------------
// Emit groups
//----------------------------------------------------------------------
DECLARE_GC_EMIT_GROUP( g_EGHTTPRequest, http_request );
CGCBase *g_pGCBase = NULL;
// Thread pool size convar
static void OnConVarChangeJobMgrThreadPoolSize( IConVar *pConVar, const char *pOldString, float flOldValue );
GCConVar jobmgr_threadpool_size( "jobmgr_threadpool_size", "-1", 0,
"Maximum threads in the job manager thread pool. Values <= 0 mean number_logical_cpus - this.",
OnConVarChangeJobMgrThreadPoolSize );
static uint32 GetThreadPoolSizeFromConVar()
{
int nVal = jobmgr_threadpool_size.GetInt();
int nRet = ( nVal > 0 ) ? nVal : GetCPUInformation()->m_nLogicalProcessors + nVal;
return (uint32)Clamp( nRet, 1, INT_MAX );
}
static void OnConVarChangeJobMgrThreadPoolSize( IConVar *pConVar, const char *pOldString, float flOldValue )
{
if ( GGCBase()->GetIsShuttingDown() )
return;
GGCBase()->GetJobMgr().SetThreadPoolSize( GetThreadPoolSizeFromConVar() );
}
GCConVar cv_concurrent_start_playing_limit( "concurrent_start_playing_limit", "1000" );
GCConVar cv_logon_surge_start_playing_limit( "logon_surge_start_playing_limit", "2000" );
GCConVar cv_logon_surge_request_session_jobs( "logon_surge_request_session_jobs", "1000" );
GCConVar cv_webapi_throttle_job_threshold( "webapi_throttle_job_threshold", "2000", 0, "If the job count exceeds this threshold, reject low-priority webapi jobs" );
GCConVar enable_startplaying_gameserver_creation_spew( "enable_startplaying_gameserver_creation_spew", "0" );
// Enable the restore-version-from-memcache machinery. Disabled because it assumes reloading an SOCache is
// deterministic, which is no longer true for us, resulting in clients with stale versions believing themselves to be in
// sync.
//
// This probably needs a look -- ideally we'd delineate deterministic objects that can be assumed to remain in sync in
// GC reboots, and dynamic objects that cannot.
//
// Note that we already removed hacks for this in player groups and started using lazy-loaded objects in SOCaches that
// violate the assumptions this was making, so re-enabling it requires work. We probably really want to split type
// caches into deterministic-between-GC-reboots and not, and resend based on said flag.
GCConVar socache_persist_version_via_memcached( "socache_persist_version_via_memcached", "0" );
static GCConVar cv_assert_minidump_window( "assert_minidump_window", "28800", 0, "Size of the minidump window in seconds. Each unique assert will dump at most assert_max_minidumps_in_window times in this many seconds" );
static GCConVar cv_assert_max_minidumps_in_window( "assert_max_minidumps_in_window", "5", 0, "The amount of times each unique assert will write a dump in assert_minidump_window seconds" );
static GCConVar cv_debug_steam_startplaying( "cv_debug_steam_startplaying", "0", 0, "Turn this ON to debug the stream of startplaying messages we get from Steam" );
static GCConVar temp_list_mismatched_replies( "temp_list_mismatched_replies", "0", "When set to 1, this report all replies that fail because the incoming message didn't expect a response. Temporary to help track down some failed state" );
static GCConVar writeback_queue_max_accumulate_time( "writeback_queue_max_accumulate_time", "10", 0, "The maximum amount of time in seconds that the writeback queue will accumulate database writes before performing queries. This is the time *before* the queries are executed, which is unbounded." );
static GCConVar writeback_queue_max_caches( "writeback_queue_max_caches", "0", 0, "The maximum amount of caches to write back in a single transaction. Set to zero to remove this restriction." );
static GCConVar geolocation_spewlevel( "geolocation_spewlevel", "4", 0, "Spewlevel to use for geolocation debug spew" );
static GCConVar geolocation_loglevel( "geolocation_loglevel", "4", 0, "Spewlevel to use for geolocation debug spew" );
extern GCConVar max_user_messages_per_second;
// There is also a GCConVar writeback_delay to control how frequently we do writebacks.
// !KLUDGE! Temp shim. Will get rid of this when we bring over the real gcinterface stuff from DOTA.
CGCInterface g_GCInterface;
CGCInterface *GGCInterface() { return &g_GCInterface; }
CSteamID CGCInterface::ConstructSteamIDForClient( AccountID_t unAccountID ) const
{
return CSteamID( unAccountID, GetUniverse(), k_EAccountTypeIndividual );
}
//-----------------------------------------------------------------------------
// Purpose: Overrides the spew func used by Msg and DMsg to print to the console
//-----------------------------------------------------------------------------
SpewRetval_t ConsoleSpewFunc( SpewType_t type, const tchar *pMsg )
{
const char *fmt = ( sizeof( tchar ) == sizeof( char ) ) ? "%hs" : "%ls";
switch (type )
{
default:
case SPEW_MESSAGE:
case SPEW_LOG:
EmitInfo( SPEW_CONSOLE, SPEW_ALWAYS, LOG_ALWAYS, fmt, pMsg );
break;
case SPEW_WARNING:
EmitWarning( SPEW_CONSOLE, SPEW_ALWAYS, fmt, pMsg );
break;
case SPEW_ASSERT:
if ( ThreadInMainThread() && ( g_pJobCur != NULL ) )
{
fmt = ( sizeof( tchar ) == sizeof( char ) ) ? "[Job %s] %hs" : "[Job %s] %ls";
EmitError( SPEW_CONSOLE, fmt, g_pJobCur->GetName(), pMsg );
}
else
{
EmitError( SPEW_CONSOLE, fmt, pMsg );
}
break;
case SPEW_ERROR:
EmitError( SPEW_CONSOLE, fmt, pMsg );
break;
}
if ( type == SPEW_ASSERT )
{
#ifndef WIN32
// Non-win32
bool bRaiseOnAssert = getenv( "RAISE_ON_ASSERT" ) || !!CommandLine()->FindParm( "-raiseonassert" );
#elif defined( _DEBUG )
// Win32 debug
bool bRaiseOnAssert = true;
#else
// Win32 release
bool bRaiseOnAssert = !!CommandLine()->FindParm( "-raiseonassert" );
#endif
return bRaiseOnAssert ? SPEW_DEBUGGER : SPEW_CONTINUE;
}
else if ( type == SPEW_ERROR )
return SPEW_ABORT;
else
return SPEW_CONTINUE;
}
class CGCShutdownJob : public CGCJob
{
public:
CGCShutdownJob( CGCBase *pGC ) : CGCJob( pGC ) {}
virtual bool BYieldingRunGCJob()
{
m_pGC->SetIsShuttingDown();
// Log off all of the game servers and users, so that if something
// in the log off dirties caches they can be written back
CUtlVector<CSteamID> vecIDsToStop;
for( CGCGSSession **ppSession = m_pGC->GetFirstGSSession(); ppSession != NULL; ppSession = m_pGC->GetNextGSSession( ppSession ) )
{
vecIDsToStop.AddToTail( (*ppSession)->GetSteamID() );
}
FOR_EACH_VEC( vecIDsToStop, i )
{
m_pGC->YieldingStopGameserver( vecIDsToStop[i] );
ShouldNotHoldAnyLocks();
}
vecIDsToStop.RemoveAll();
for( CGCUserSession **ppSession = m_pGC->GetFirstUserSession(); ppSession != NULL; ppSession = m_pGC->GetNextUserSession( ppSession ) )
{
vecIDsToStop.AddToTail( (*ppSession)->GetSteamID() );
}
FOR_EACH_VEC( vecIDsToStop, i )
{
m_pGC->YieldingStopPlaying( vecIDsToStop[i] );
ShouldNotHoldAnyLocks();
}
// wait for jobs to finish (except this one!)
const int kMaxIterations = 100;
int cIter = 0;
while ( cIter++ < kMaxIterations && m_pGC->GetJobMgr().CountJobs() > 1 )
{
BYieldingWaitOneFrame();
}
m_pGC->YieldingGracefulShutdown();
GGCHost()->ShutdownComplete();
return false;
}
};
class CPreTestSetupJob : public CGCJob
{
public:
CPreTestSetupJob( CGCBase *pGC ) : CGCJob( pGC ) {}
virtual bool BYieldingRunGCJob( GCSDK::CNetPacket *pNetPacket )
{
CGCMsg<MsgGCEmpty_t> msg( pNetPacket );
m_pGC->YieldingPreTestSetup();
return true;
}
};
GC_REG_JOB( CGCBase, CPreTestSetupJob, "CPreTestSetupJob", k_EGCMsgPreTestSetup, k_EServerTypeGC );
static void SpewSerializedKeyValues( const byte *pubVarData, uint32 cubVarData )
{
if ( pubVarData == NULL || cubVarData == 0 )
{
EmitInfo( SPEW_GC, 1, 1, " No KV data\n" );
return;
}
char szLine[512] = "";
for ( uint32 i = 0 ; i < cubVarData ; ++i )
{
char szByteVal[32];
V_sprintf_safe( szByteVal, "%02X", pubVarData[ i ] );
if ( i % 32 )
{
V_strcat_safe( szLine, ", " );
V_strcat_safe( szLine, szByteVal );
}
else
{
if ( szLine[0] )
EmitInfo( SPEW_GC, 1, 1, " %s\n", szLine );
V_strcpy_safe( szLine, szByteVal );
}
}
if ( szLine[0] )
EmitInfo( SPEW_GC, 1, 1, " %s\n", szLine );
KeyValuesAD pkvDetails( "SessionDetails" );
CUtlBuffer buf;
buf.Put( pubVarData, cubVarData );
if( pkvDetails->ReadAsBinary( buf ) )
{
FOR_EACH_VALUE( pkvDetails, v )
{
EmitInfo( SPEW_GC, 1, 1, " %s = %s\n", v->GetName(), v->GetString( NULL, "??" ) );
}
}
else
{
EmitInfo( SPEW_GC, 1, 1, " KV data failed parse\n" );
}
}
class CStartPlayingJob : public CGCJob
{
public:
CStartPlayingJob( CGCBase *pGC ) : CGCJob( pGC ) {}
virtual bool BYieldingRunGCJob( GCSDK::IMsgNetPacket *pNetPacket )
{
CGCMsg<MsgGCStartPlaying_t> msg( pNetPacket );
// @note Tom Bui/Joe Ludwig: This can happen for PS3 Steam accounts
if ( !msg.Body().m_steamID.IsValid() )
return true;
if ( cv_debug_steam_startplaying.GetBool() )
{
netadr_t serverAdr( msg.Body().m_unServerAddr, msg.Body().m_usServerPort );
EmitInfo( SPEW_GC, 1, 1, "Received StartPlaying( user = %s, GS = %s @ %s )\n", msg.Body().m_steamID.Render(), msg.Body().m_steamIDGS.Render(), serverAdr.ToString() );
SpewSerializedKeyValues( msg.PubVarData(), msg.CubVarData() );
}
m_pGC->QueueStartPlaying( msg.Body().m_steamID, msg.Body().m_steamIDGS, msg.Body().m_unServerAddr, msg.Body().m_usServerPort, msg.PubVarData(), msg.CubVarData() );
return true;
}
};
GC_REG_JOB(CGCBase, CStartPlayingJob, "CStartPlayingJob", k_EGCMsgStartPlaying, k_EServerTypeGC);
class CExecuteStartPlayingJob : public CGCJob
{
public:
CExecuteStartPlayingJob( CGCBase *pGC ) : CGCJob( pGC ) {}
virtual bool BYieldingRunGCJob( )
{
m_pGC->YieldingExecuteNextStartPlaying();
return true;
}
};
class CStopPlayingJob : public CGCJob
{
public:
CStopPlayingJob( CGCBase *pGC ) : CGCJob( pGC ) {}
virtual bool BYieldingRunGCJob( GCSDK::IMsgNetPacket *pNetPacket )
{
CGCMsg<MsgGCStopSession_t> msg( pNetPacket );
// @note Tom Bui/Joe Ludwig: This can happen for PS3 Steam accounts
if ( !msg.Body().m_steamID.IsValid() )
return true;
if ( cv_debug_steam_startplaying.GetBool() )
{
EmitInfo( SPEW_GC, 1, 1, "Received StopPlaying( user = %s )\n", msg.Body().m_steamID.Render() );
}
m_pGC->YieldingStopPlaying( msg.Body().m_steamID );
return true;
}
};
GC_REG_JOB(CGCBase, CStopPlayingJob, "CStopPlayingJob", k_EGCMsgStopPlaying, k_EServerTypeGC);
class CStartGameserverJob : public CGCJob
{
public:
CStartGameserverJob( CGCBase *pGC ) : CGCJob( pGC ) {}
virtual bool BYieldingRunGCJob( GCSDK::IMsgNetPacket *pNetPacket )
{
CGCMsg<MsgGCStartGameserver_t> msg( pNetPacket );
m_pGC->QueueStartPlaying( msg.Body().m_steamID, CSteamID(), msg.Body().m_unServerAddr, msg.Body().m_usServerPort, msg.PubVarData(), msg.CubVarData() );
return true;
}
};
GC_REG_JOB(CGCBase, CStartGameserverJob, "CStartGameserverJob", k_EGCMsgStartGameserver, k_EServerTypeGC);
class CStopGameserverJob : public CGCJob
{
public:
CStopGameserverJob( CGCBase *pGC ) : CGCJob( pGC ) {}
virtual bool BYieldingRunGCJob( GCSDK::IMsgNetPacket *pNetPacket )
{
CGCMsg<MsgGCStopSession_t> msg( pNetPacket );
m_pGC->YieldingStopGameserver( msg.Body().m_steamID );
return true;
}
};
GC_REG_JOB(CGCBase, CStopGameserverJob, "CStopGameserverJob", k_EGCMsgStopGameserver, k_EServerTypeGC);
class CGetSystemStatsJob : public CGCJob
{
public:
CGetSystemStatsJob( CGCBase *pGC ) : CGCJob( pGC ) {}
virtual bool BYieldingRunGCJob( GCSDK::IMsgNetPacket *pNetPacket )
{
CProtoBufMsg<CGCMsgGetSystemStats> msg( pNetPacket );
CProtoBufMsg<CGCMsgGetSystemStatsResponse> msgResponse( k_EGCMsgGetSystemStatsResponse );
msgResponse.Body().set_gc_app_id( m_pGC->GetAppID() );
// @note Tom Bui: we don't support dynamic stats yet, but once we do, we can use the KV stuff
m_pGC->SystemStats_Update( msgResponse.Body() );
// KVPacker packer;
// KeyValuesAD pKVStats( "GCStats" );
// CUtlBuffer buffer;
// if ( packer.WriteAsBinary( pKVStats, buffer ) )
// {
// msgResponse.Body().set_stats_kv( buffer.Base(), buffer.TellPut() );
// }
return m_pGC->BSendSystemMessage( msgResponse );
}
};
GC_REG_JOB(CGCBase, CGetSystemStatsJob, "CGetSystemStatsJob", k_EGCMsgGetSystemStats, k_EServerTypeGC);
//-----------------------------------------------------------------------------
class CGCJobAccountVacStatusChange : public CGCJob
{
public:
CGCJobAccountVacStatusChange( CGCBase *pGC ) : CGCJob( pGC ) {}
bool BYieldingRunJobFromMsg( IMsgNetPacket *pNetPacket )
{
CProtoBufMsg<CMsgGCHAccountVacStatusChange> msg( pNetPacket );
if ( GGCBase()->GetAppID() != msg.Body().app_id() )
return true;
CSteamID steamID( msg.Body().steam_id() );
bool bIsVacBanned = msg.Body().is_banned_now();
// Fetch app details, but force them to be re-loaded
bool bForceReload = true;
const CAccountDetails *pAccountDetails = GGCBase()->YieldingGetAccountDetails( steamID, bForceReload );
// Account details is up to date so just return
if ( pAccountDetails && bIsVacBanned != pAccountDetails->BIsVacBanned() )
{
EmitWarning( SPEW_GC, 2, "VAC status didn't update for %s afetr receiving VacStatusChange and the force reloading the account details\n", steamID.Render() );
}
return true;
}
};
GC_REG_JOB( CGCBase, CGCJobAccountVacStatusChange, "CGCJobAccountVacStatusChange", k_EGCMsgGCAccountVacStatusChange, k_EServerTypeGC );
//-----------------------------------------------------------------------------
class CGCJobAccountPhoneNumberChange : public CGCJob
{
public:
CGCJobAccountPhoneNumberChange( CGCBase *pGC ) : CGCJob( pGC ) {}
bool BYieldingRunJobFromMsg( IMsgNetPacket *pNetPacket )
{
CProtoBufMsg<CMsgGCHAccountPhoneNumberChange> msg( pNetPacket );
if ( GGCBase()->GetAppID() != msg.Body().appid() )
return true;
CSteamID steamID( msg.Body().steamid() );
CScopedSteamIDLock scopedLock( steamID );
if ( !scopedLock.BYieldingPerformLock( __FILE__, __LINE__ ) )
{
EmitError( SPEW_GC, __FUNCTION__ ": Failed to lock steamid %s\n", steamID.Render() );
return true;
}
bool bHasPhoneVerified = msg.Body().is_verified();
bool bIsPhoneIdentifying = msg.Body().is_identifying();
// Fetch app details, but force them to be re-loaded
bool bForceReload = true;
const CAccountDetails *pAccountDetails = GGCBase()->YieldingGetAccountDetails( steamID, bForceReload );
// Account details is up to date so just return
if ( pAccountDetails && ( bHasPhoneVerified != pAccountDetails->BIsPhoneVerified() ||
bIsPhoneIdentifying != pAccountDetails->BIsPhoneIdentifying() ) )
{
EmitWarning( SPEW_GC, 2, "Phone status didn't update for %s afetr receiving PhoneNumberChange and force reloading the account details\n",
steamID.Render() );
}
GGCBase()->YldOnAccountPhoneVerificationChange( steamID );
EmitInfo( SPEW_GC, 5, 5, "AccountPhoneVerificationChange for %s\n", steamID.Render() );
return true;
}
};
GC_REG_JOB( CGCBase, CGCJobAccountPhoneNumberChange, "CGCJobAccountPhoneNumberChange", k_EGCMsgAccountPhoneNumberChange, k_EServerTypeGC );
//-----------------------------------------------------------------------------
class CGCJobAccountTwoFactorChange : public CGCJob
{
public:
CGCJobAccountTwoFactorChange( CGCBase *pGC ) : CGCJob( pGC ) {}
bool BYieldingRunJobFromMsg( IMsgNetPacket *pNetPacket )
{
CProtoBufMsg<CMsgGCHAccountTwoFactorChange> msg( pNetPacket );
if ( GGCBase()->GetAppID() != msg.Body().appid() )
return true;
CSteamID steamID( msg.Body().steamid() );
bool bHasTwoFactor = msg.Body().twofactor_enabled();
// Fetch app details, but force them to be re-loaded
bool bForceReload = true;
const CAccountDetails *pAccountDetails = GGCBase()->YieldingGetAccountDetails( steamID, bForceReload );
// Account details is up to date so just return
if ( pAccountDetails && bHasTwoFactor != pAccountDetails->BIsTwoFactorAuthEnabled() )
{
EmitWarning( SPEW_GC, 2, "VAC status didn't update for %s afetr receiving VacStatusChange and the force reloading the account details\n", steamID.Render() );
}
GGCBase()->YldOnAccountTwoFactorChange( steamID );
EmitInfo( SPEW_GC, 5, 5, "AccountTwoFactorChange for %s\n", steamID.Render() );
return true;
}
};
GC_REG_JOB( CGCBase, CGCJobAccountTwoFactorChange, "CGCJobAccountTwoFactorChange", k_EGCMsgAccountTwoFactorChange, k_EServerTypeGC );
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CGCBase::CGCBase( )
: m_mapSOCache( ),
m_rbtreeSOCachesBeingLoaded( DefLessFunc( CSteamID ) ),
m_rbtreeSOCachesWithDirtyVersions( DefLessFunc( CSteamID ) ),
m_hashUserSessions( k_nUserSessionRunInterval/ k_cMicroSecPerShellFrame ),
m_hashGSSessions( k_nGSSessionRunInterval/ k_cMicroSecPerShellFrame ),
m_hashSteamIDLocks( k_nLocksRunInterval / k_cMicroSecPerShellFrame ),
m_bStartupComplete( false ),
m_bIsShuttingDown( false ),
m_bStartProfiling( false ),
m_bStopProfiling( false ),
m_bDumpVprofImbalances( false ),
m_nStartPlayingJobCount( 0 ),
m_nRequestSessionJobsActive( 0 ),
m_nLogonSurgeFramesRemaining( k_nMillion * 10 / k_cMicroSecPerShellFrame ), // stay in "logon surge" mode for at least 10 seconds after boot.
m_mapStartPlayingQueueIndexBySteamID( DefLessFunc( CSteamID ) ),
m_MsgRateLimit( max_user_messages_per_second ),
m_nStartupCompleteTime( CRTime::RTime32TimeCur() ),
m_nInitTime( CRTime::RTime32TimeCur() ),
m_jobidFlushInventoryCacheAccounts( k_GIDNil ),
m_numFlushInventoryCacheAccountsLastScheduled( 0 )
{
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CGCBase::~CGCBase()
{
}
//-----------------------------------------------------------------------------
// Purpose: Remembers the app ID and host
//-----------------------------------------------------------------------------
bool CGCBase::BInit( AppId_t unAppID, const char *pchAppPath, IGameCoordinatorHost *pHost )
{
VPROF_BUDGET( "CGCBase::BInit", VPROF_BUDGETGROUP_STEAM );
// Make sure we can't deploy debug GCs outside the dev environment
#ifdef _DEBUG
if ( pHost->GetUniverse() != k_EUniverseDev )
{
//pHost->EmitMessage( SPEW_GC, SPEW_ERROR, SPEW_ALWAYS, LOG_ALWAYS,
// CFmtStr( "The GC for App %u is a debug binary. Shutting down.\n", unAppID ) );
//return false;
pHost->EmitMessage( SPEW_GC.GetName(), SPEW_WARNING, SPEW_ALWAYS, LOG_ALWAYS,
CFmtStr( "The GC for App %u is a debug binary.\n", unAppID ) );
}
#endif
m_JobMgr.SetThreadPoolSize( GetThreadPoolSizeFromConVar() );
MsgRegistrationFromEnumDescriptor( EGCSystemMsg_descriptor(), GCSDK::MT_GC_SYSTEM );
MsgRegistrationFromEnumDescriptor( EGCBaseClientMsg_descriptor(), GCSDK::MT_GC );
MsgRegistrationFromEnumDescriptor( EGCToGCMsg_descriptor(), GCSDK::MT_GC_SYSTEM );
m_unAppID = unAppID;
m_pHost = pHost;
m_sPath = pchAppPath;
SetGCHost( pHost );
g_pGCBase = this;
SetMinidumpFilenamePrefix( CFmtStr("dumps\\gc%d", m_unAppID) );
// Make sure the assert dialog doesn't come up and hang the process in production
//SetAssertDialogDisabled( pHost->GetUniverse() != k_EUniverseDev );
SetAssertFailedNotifyFunc( CGCBase::AssertCallbackFunc );
// init the time very early so CRTime::RTime32TimeCur will return the right thing
CRTime::UpdateRealTime();
m_hashUserSessions.Init( k_cGCUserSessionInit, k_cBucketGCUserSession );
m_hashGSSessions.Init( k_cGCGSSessionInit, k_cBucketGCGSSession );
m_hashSteamIDLocks.Init( k_cGCLocksInit, k_cBucketGCLocks );
m_OutputFuncPrev = GetSpewOutputFunc();
SpewOutputFunc( &ConsoleSpewFunc );
EmitInfo( SPEW_GC, 1, 1, "CGCBase::BInit( AppID=%d, appPath=%s, sPath=%s )\n", unAppID, pchAppPath, m_sPath.String() );
if ( !OnInit() )
return false;
DbgVerify( g_theMessageList.BInit( ) );
/*
// @note Tom Bui: we don't need dynamic stats...yet.
// when we do, we'll need to specify the how the values are aggregated over all the same GCs
// and how the values should be treated
KeyValuesAD pKVStats( "GCStats" );
SystemStats_Update( pKVStats );
CUtlBuffer buffer;
KVPacker packer;
if ( packer.WriteAsBinary( pKVStats, buffer ) )
{
CProtoBufMsg< CGCMsgSystemStatsSchema > msg( GCSDK::k_EGCMsgSystemStatsSchema );
msg.Body().set_gc_app_id( GetAppID() );
msg.Body().set_schema_kv( buffer.Base(), buffer.TellPut() );
BSendSystemMessage( msg );
}
*/
return BSendWebApiRegistration();
}
//-----------------------------------------------------------------------------
// Purpose: Report back to the host that startup is complete
//-----------------------------------------------------------------------------
void CGCBase::SetStartupComplete( bool bSuccess )
{
// !KLUDGE! Fatal error messages on startup frequently get lost in the
// mass of messages. Let's spray a big error message box if we fail
// to startup. Ideally, the cause of the failure will be
// spewed just above this box.
if ( !bSuccess )
{
EmitError( SPEW_GC, "^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^\n" );
EmitError( SPEW_GC, "GC failed to startup. Error mesage is probably directly above\n" );
EmitError( SPEW_GC, "**************************************************************\n" );
}
m_nStartupCompleteTime = CRTime::RTime32TimeCur();
m_bStartupComplete = true;
GGCHost()->StartupComplete( bSuccess );
}
uint32 CGCBase::GetGCUpTime() const
{
return CRTime::RTime32TimeCur() - m_nInitTime;
}
//-----------------------------------------------------------------------------
// Purpose: Starts a job to perform graceful shutdown
//-----------------------------------------------------------------------------
void CGCBase::Shutdown()
{
VPROF_BUDGET( "CGCBase::Shutdown", VPROF_BUDGETGROUP_STEAM );
m_DumpHTTPErrorsSchedule.Cancel();
CGCShutdownJob *pJob = new CGCShutdownJob( this );
pJob->StartJob( NULL );
}
//-----------------------------------------------------------------------------
// Purpose: Cleans up the GC to prepare for shutdown
//-----------------------------------------------------------------------------
void CGCBase::Uninit( )
{
VPROF_BUDGET( "CGCBase::Uninit", VPROF_BUDGETGROUP_STEAM );
OnUninit();
// clean up all of the sessions and caches here so we can be sure it happens before the memory pools go away at static destruction time
for( CGCUserSession **ppSession = m_hashUserSessions.PvRecordFirst(); ppSession != NULL; ppSession = m_hashUserSessions.PvRecordNext( ppSession ) )
{
delete (*ppSession);
}
m_hashUserSessions.RemoveAll();
for( CGCGSSession **ppSession = m_hashGSSessions.PvRecordFirst(); ppSession != NULL; ppSession = m_hashGSSessions.PvRecordNext( ppSession ) )
{
delete (*ppSession);
}
m_hashGSSessions.RemoveAll();
FOR_EACH_MAP_FAST( m_mapSOCache, nIndex )
{
// Remove from map before deleting, to prevent some debug
// code from getting tangled up
CGCSharedObjectCache *pCache = m_mapSOCache[nIndex];
m_mapSOCache[nIndex] = NULL;
m_mapSOCache.RemoveAt( nIndex );
delete pCache;
}
m_mapSOCache.RemoveAll();
m_rbtreeSOCachesBeingLoaded.RemoveAll();
m_rbtreeSOCachesWithDirtyVersions.RemoveAll();
m_hashSteamIDLocks.RemoveAll();
GSchemaFull().Uninit();
SpewOutputFunc( m_OutputFuncPrev );
}
GCConVar cv_flush_inventory_cache_jobs( "cv_flush_inventory_cache_jobs", "20", 0, "The maximum number of jobs flushing inventory caches that can be in flight at once, zero to disable flushing" );
GCConVar cv_flush_inventory_cache_contextid( "cv_flush_inventory_cache_contextid", "2" /* k_EEconContextBackpack */, 0, "Which context id we flush for Steam web user-facing inventory" );
GCConVar cv_flush_inventory_cache_spew( "cv_flush_inventory_cache_spew", "0", 0, "Controls spew level for jobs flushing inventory cache (0=off; 1=summary; 2=verbose)" );
class CFlushInventoryCacheAccountsJob : public CGCJob, public IYieldingParallelFarmJobHandler
{
public:
CFlushInventoryCacheAccountsJob( CGCBase *pGC, CUtlRBTree< AccountID_t, int32, CDefLess< AccountID_t > > &rbAccounts ) : CGCJob( pGC )
{
m_rbAccounts.Swap( rbAccounts );
}
virtual bool BYieldingRunGCJob() OVERRIDE
{
if ( !m_rbAccounts.Count() )
return false;
if ( cv_flush_inventory_cache_jobs.GetInt() <= 0 )
return false;
bool bShouldSpew = ( cv_flush_inventory_cache_spew.GetInt() >= 1 );
uint32 msTimeStart = 0;
int numAccountsWorkload = m_rbAccounts.Count();
if ( bShouldSpew )
{
msTimeStart = Plat_MSTime();
}
{ // Run parallel processing of the workload
int numJobs = numAccountsWorkload;
numJobs = MIN( cv_flush_inventory_cache_jobs.GetInt(), numJobs );
numJobs = MAX( 1, numJobs );
( void ) BYieldingExecuteParallel( numJobs, "YieldingFlushInventoryCacheAccountsJob" );
}
if ( bShouldSpew )
{
EmitInfo( SPEW_GC, SPEW_ALWAYS, LOG_ALWAYS, "IEconService/FlushInventoryCache: Batch for %d accounts completed in %u ms\n",
numAccountsWorkload, Plat_MSTime() - msTimeStart );
}
return true;
}
virtual bool BYieldingRunWorkload( int iJobSequenceCounter, bool *pbWorkloadCompleted ) OVERRIDE
{
if ( m_rbAccounts.Count() )
{
int32 idxElement = m_rbAccounts.FirstInorder();
AccountID_t unAccountID = m_rbAccounts.Element( idxElement );
m_rbAccounts.RemoveAt( idxElement );
( void ) BYieldingFlushRequest( unAccountID );
}
if ( !m_rbAccounts.Count() )
{
*pbWorkloadCompleted = true;
}
return true;
}
bool BYieldingFlushRequest( AccountID_t unAccountID )
{
bool bShouldSpew = ( cv_flush_inventory_cache_spew.GetInt() >= 2 );
uint32 msTimeStart = 0;
if ( bShouldSpew )
{
msTimeStart = Plat_MSTime();
}
CSteamID steamID( GGCInterface()->ConstructSteamIDForClient( unAccountID ) );
CSteamAPIRequest apiRequest( k_EHTTPMethodPOST, "IEconService", "FlushInventoryCache", 1 );
apiRequest.SetPOSTParamUInt32( "appid", GGCBase()->GetAppID() );
apiRequest.SetPOSTParamUInt64( "steamid", steamID.ConvertToUint64() );
apiRequest.SetPOSTParamUInt32( "contextid", 2 );
CHTTPResponse apiResponse;
bool bSucceededQuery = m_pGC->BYieldingSendHTTPRequest( &apiRequest, &apiResponse );
if ( !bSucceededQuery )
{
EmitErrorRatelimited( SPEW_GC, "IEconService/FlushInventoryCache: Web call did not get a response for %s.\n", steamID.Render() );
}
else if ( k_EHTTPStatusCode200OK != apiResponse.GetStatusCode() )
{
EmitErrorRatelimited( SPEW_GC, "IEconService/FlushInventoryCache: Web call got failure code %d for %s\n", apiResponse.GetStatusCode(), steamID.Render() );
bSucceededQuery = false;
}
if ( bSucceededQuery )
{
// Have a valid response
KeyValuesAD pKVResponse( "response" );
pKVResponse->UsesEscapeSequences( true );
if ( !pKVResponse->LoadFromBuffer( "webResponse", *apiResponse.GetBodyBuffer() ) )
{
EmitErrorRatelimited( SPEW_GC, "IEconService/FlushInventoryCache: Web call got code %d for %s, but failed to parse response\n", apiResponse.GetStatusCode(), steamID.Render() );
bSucceededQuery = false;
}
else if ( !pKVResponse->GetBool( "success" ) )
{
// We got a response, and it's not success
EmitErrorRatelimited( SPEW_GC, "IEconService/FlushInventoryCache: Web call got code %d for %s, but not success\n", apiResponse.GetStatusCode(), steamID.Render() );
bSucceededQuery = false;
}
}
if ( bShouldSpew )
{
EmitInfo( SPEW_GC, SPEW_ALWAYS, LOG_ALWAYS, "IEconService/FlushInventoryCache: Web call for %s %s in %u ms\n",
steamID.Render(), bSucceededQuery ? "succeeded" : "failed", Plat_MSTime() - msTimeStart );
}
return bSucceededQuery;
}
public:
CUtlRBTree< AccountID_t, int32, CDefLess< AccountID_t > > m_rbAccounts;
};
//-----------------------------------------------------------------------------
// Purpose: Called every frame. Mostly updates times and pulses the job manager
//-----------------------------------------------------------------------------
bool CGCBase::BMainLoopOncePerFrame( uint64 ulLimitMicroseconds )
{
// if we don't have a GCHost yet, don't do any work per frame
if( !GGCHost() )
return false;
#ifndef STEAM
CRTime::UpdateRealTime();
#endif
#ifdef VPROF_ENABLED
// Make sure we end the frame at the root node
if ( !g_VProfCurrentProfile.AtRoot() && m_bDumpVprofImbalances )
{
EmitWarning( SPEW_GC, SPEW_ALWAYS, "VProf not at root at end of frame. Stack:\n" );
}
for( int i = 0; !g_VProfCurrentProfile.AtRoot() && i < 100; i++ )
{
if ( m_bDumpVprofImbalances )
{
EmitWarning( SPEW_GC, SPEW_ALWAYS, " %s\n", g_VProfCurrentProfile.GetCurrentNode()->GetName() );
}
g_VProfCurrentProfile.ExitScope();
}
g_VProfCurrentProfile.MarkFrame();
if ( m_bStopProfiling || m_bStartProfiling )
{
while ( g_VProfCurrentProfile.IsEnabled() )
{
g_VProfCurrentProfile.Stop();
}
m_bStopProfiling = false;
if ( m_bStartProfiling )
{
g_VProfCurrentProfile.Reset();
g_VProfCurrentProfile.Start();
m_bStartProfiling = false;
}
}
#endif
VPROF_BUDGET( "Main Loop", VPROF_BUDGETGROUP_STEAM );
CLimitTimer limitTimer;
limitTimer.SetLimit( ulLimitMicroseconds );
CJobTime::UpdateJobTime( k_cMicroSecPerShellFrame );
bool bWorkRemaining = m_JobMgr.BFrameFuncRunSleepingJobs( limitTimer );
//run all of our frame functions
GFrameFunctionMgr().RunFrame( limitTimer );
{
VPROF_BUDGET( "Run Sessions", VPROF_BUDGETGROUP_STEAM );
m_AccountDetailsManager.MarkFrame();
m_hashUserSessions.StartFrameSchedule( true );
m_hashGSSessions.StartFrameSchedule( true );
m_hashSteamIDLocks.StartFrameSchedule( true );
bool bUsersFinished = false, bGSFinished = false;
while( !limitTimer.BLimitReached() && ( !bUsersFinished || !bGSFinished ) )
{
if( !bUsersFinished )
{
CGCUserSession **ppSession = m_hashUserSessions.PvRecordRun();
if ( ppSession && *ppSession )
{
(*ppSession)->Run();
}
else
{
bUsersFinished = true;
}
if ( m_hashUserSessions.BCompletedPass() )
{
FinishedMainLoopUserSweep();
}
}
if( !bGSFinished )
{
CGCGSSession **ppSession = m_hashGSSessions.PvRecordRun();
if ( ppSession && *ppSession )
{
(*ppSession)->Run();
}
else
{
bGSFinished = true;
}
}
}
}
{
VPROF_BUDGET( "UpdateSOCacheVersions", VPROF_BUDGETGROUP_STEAM );
UpdateSOCacheVersions();
}
if( m_llStartPlaying.Count() > 0 )
{
VPROF_BUDGET( "StartStartPlayingJobs", VPROF_BUDGETGROUP_STEAM );
int nJobsNeeded = min( m_llStartPlaying.Count(), cv_concurrent_start_playing_limit.GetInt() - m_nStartPlayingJobCount );
while( nJobsNeeded > 0 )
{
nJobsNeeded--;
m_nStartPlayingJobCount++;
CExecuteStartPlayingJob *pJob = new CExecuteStartPlayingJob( this );
pJob->StartJob( NULL );
}
}
// Decide if we should be in logon surge
bool bShouldBeInlogonSurge =
m_llStartPlaying.Count() >= cv_logon_surge_start_playing_limit.GetInt();
// This might be a good idea, but let's see what the real numbers are during logon surge.
//|| m_nRequestSessionJobsActive >= cv_logon_surge_request_session_jobs.GetInt();
// Check if we're already in logon surge, is it time to check if we should leave,
// and should we dump our status periodically?
const int k_nLogonSurgeFrameInterval = k_nMillion * 10 / k_cMicroSecPerShellFrame;
if ( m_nLogonSurgeFramesRemaining > 0 )
{
// Currently in logon surge
--m_nLogonSurgeFramesRemaining;
if ( m_nLogonSurgeFramesRemaining == 0 )
{
// Time to check for leaving logon surge mode.
// Should I flip the flag off?
if ( bShouldBeInlogonSurge )
{
// We're still in logon surge. Schedule another check
// a few frames from now, and dump our status.
m_nLogonSurgeFramesRemaining = k_nLogonSurgeFrameInterval;
Dump();
}
else
{
// We're over the hump!
EmitInfo( SPEW_GC, SPEW_ALWAYS, LOG_ALWAYS, "** LOGON SURGE COMPLETED **\n" );
}
}
}
else if ( bShouldBeInlogonSurge )
{
// We finished logon surge one, but now we are re-entering it.
// This usually doesn't happen. This is suspicious.
EmitWarning( SPEW_GC, SPEW_ALWAYS, "RE-ENTERING logon surge mode!\n" );
m_nLogonSurgeFramesRemaining = k_nLogonSurgeFrameInterval;
}
else
{
// Not in logon surge. make sure flag is slammed to zero
m_nLogonSurgeFramesRemaining = 0;
}
// Flush inventory cache for accounts
if ( m_rbFlushInventoryCacheAccounts.Count() && ( ( m_jobidFlushInventoryCacheAccounts == k_GIDNil ) ||
!GetJobMgr().BJobExists( m_jobidFlushInventoryCacheAccounts ) ) )
{
m_numFlushInventoryCacheAccountsLastScheduled = m_rbFlushInventoryCacheAccounts.Count();
m_jobidFlushInventoryCacheAccounts = StartNewJobDelayed( new CFlushInventoryCacheAccountsJob( this, m_rbFlushInventoryCacheAccounts ) )->GetJobID();
}
bool bSubRet = OnMainLoopOncePerFrame( limitTimer );
return bWorkRemaining || bSubRet;
}
bool CGCBase::BShouldThrottleLowServiceLevelWebAPIJobs() const
{
// Always throttle them during logon surge.
if ( BIsInLogonSurge() )
return true;
// Check threshold
if ( m_JobMgr.CountJobs() > cv_webapi_throttle_job_threshold.GetInt() )
return true;
// We are not too busy, we can service the request
return false;
}