void killAllWERProcesses(void) { DWORD werFault = getProcessID("WerFault.exe"); while (werFault != 0) { killProcessByID(werFault); Sleep(1000); werFault = getProcessID("WerFault.exe"); } } // end of killAllWERProcesses()
void StopPlayRadio() { int pid = getProcessID("ffplay"); //printf("id=%d",pid); if(pid!=-1) kill(pid,SIGTERM); }
void StartPlayRadio() { int pid = getProcessID("ffplay"); //printf("id=%d",pid); if(pid==-1) system("ffplay -nodisp mmsh://bcr.media.hinet.net/RA000042 &"); }
////////////////////////////////////////////////////////////////////////// //! LogerManager ////////////////////////////////////////////////////////////////////////// LogerManager::LogerManager() { _runing = false; _lastId = LOG4Z_MAIN_LOGGER_ID; _hotUpdateInterval = 0; _ullStatusTotalPushLog = 0; _ullStatusTotalPopLog = 0; _ullStatusTotalWriteFileCount = 0; _ullStatusTotalWriteFileBytes = 0; _pid = getProcessID(); _proName = getProcessName(); _loggers[LOG4Z_MAIN_LOGGER_ID]._enable = true; _ids[LOG4Z_MAIN_LOGGER_KEY] = LOG4Z_MAIN_LOGGER_ID; _loggers[LOG4Z_MAIN_LOGGER_ID]._key = LOG4Z_MAIN_LOGGER_KEY; _loggers[LOG4Z_MAIN_LOGGER_ID]._name = _proName; }
void ServiceStop() { printf("call ServiceStop\n"); printf("Search for %s\n",__progname); pid_t pidSelf; pidSelf = getpid(); int pid = -1; pid = getProcessID(__progname); printf("self pid=%d\n",pidSelf); printf("pid=%d\n",pid); if(pid!=-1 && pid!=0) { printf("call kill\n"); kill(pid,SIGTERM); } printf("call ServiceStop end\n"); }
int main(int argc, char **argv) { int port = 5586, notification_timeout = 5, config_preceeds = 1, sockfd, newsockfd, c; socklen_t clilen; char msg[256]; char buffer[256]; struct sockaddr_in serv_addr, cli_addr; while (1) { static struct option long_options[] = { /* These options don't set a flag. * We distinguish them by their indices. */ {"port", required_argument, 0, 'p'}, {"timeout", required_argument, 0, 't'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; c = getopt_long (argc, argv, "hp:t:", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 0: /* If this option set a flag, do nothing else now. */ if (long_options[option_index].flag != 0) break; printf ("option %s", long_options[option_index].name); if (optarg) printf (" with arg %s", optarg); printf ("\n"); break; case 'p': port = atoi(optarg); config_preceeds = 0; break; case 't': notification_timeout = atoi(optarg); config_preceeds = 0; break; case 'h': printf ("Usage:\n"); printf ("%s [-h] [-p port_number] [-t notification_timeout]\n", argv[0]); exit(EXIT_SUCCESS); case '?': /* getopt_long already printed an error message. */ break; default: printf("Unkown parameter. Exiting.\n"); exit(EXIT_FAILURE); } } /* Our process ID and Session ID */ pid_t pid, sid, pid_found; dictionary *dict; /* Fork off the parent process */ pid = fork(); if (pid < 0) { printf("Cannot fork the daemon. Exiting...\n"); exit(EXIT_FAILURE); } /* If we got a good PID, then * we can exit the parent process. */ if (pid > 0) { exit(EXIT_SUCCESS); } /* Change the file mode mask */ umask(0); openlog ("notifmed", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL0); syslog (LOG_INFO, "Program started by user %d", getuid ()); if (config_preceeds) { char * home = getenv("HOME"); char * home_path_config = malloc(snprintf(NULL, 0, "%s/%s", home, ".notifmedrc") + 1); sprintf(home_path_config, "%s/%s", home, ".notifmedrc"); if (file_exists(home_path_config)) { dict = iniparser_load(home_path_config); } else if (file_exists("/etc/notifmed.rc")) { dict = iniparser_load("/etc/notifmed.rc"); /* a config file could also be given as argument } else if (file_exists()) { dict = iniparser_load();*/ } else { syslog (LOG_INFO, "No configuration file found."); syslog (LOG_INFO, "Using defaults:"); syslog (LOG_INFO, " port = 5586 ; notification_timeout = 5"); } if (!dict) { syslog (LOG_ERR, "Dictionary configuration file problem."); closelog(); exit(EXIT_FAILURE); } int i; unsigned int hh=dictionary_hash("server"); for ( i=0 ; (i<dict->n) && (hh!=dict->hash[i]) ; i++); // No "server" section found if( i == dict->n ) { syslog (LOG_INFO, "No server section found."); syslog (LOG_INFO, "Using defaults:"); syslog (LOG_INFO, " port = 5586 ; notification_timeout = 5"); } for ( i++ ; ( i < dict->n ) && strncmp(dict->key[i],"server:",6) == 0 ; i++ ) { if (strcmp(dict->key[i],"server:port") == 0) { port = atoi(dict->val[i]); } else if (strcmp(dict->key[i],"server:notification_timeout") == 0) { notification_timeout = atoi(dict->val[i]); } } } syslog (LOG_INFO, "Config found: port=%i - notification_timeout=%i", port, notification_timeout); /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { syslog (LOG_ERR, "Cannot create a new SID."); closelog(); exit(EXIT_FAILURE); } // Preparing the network part sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { syslog (LOG_ERR, "Cannot open the socket."); closelog(); exit(EXIT_FAILURE); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(port); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { syslog (LOG_ERR, "Cannot bind the socket."); closelog(); exit(EXIT_FAILURE); } listen(sockfd,5); clilen = sizeof(cli_addr); /* Change the current working directory */ if ((chdir("/")) < 0) { syslog (LOG_ERR, "Cannot create a new SID."); closelog(); exit(EXIT_FAILURE); } /* Close out the standard file descriptors */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); NotifyNotification *n; notify_init("Initialization"); n = notify_notification_new ("notifmed","Initialized!\nMonitoring for client requests...", NULL); notify_notification_set_timeout(n, notification_timeout * 1000); //3 seconds if (!notify_notification_show (n, NULL)) { g_error("Failed to send notification.\n"); return 1; } g_object_unref(G_OBJECT(n)); /* The Big Loop */ while (1) { newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) { syslog (LOG_ERR, "Cannot accept messages."); closelog(); close(newsockfd); close(sockfd); exit(EXIT_FAILURE); } bzero(buffer,256); n = read(newsockfd,buffer,255); if (n < 0) { syslog (LOG_ERR, "Error reading from the socket."); closelog(); close(newsockfd); close(sockfd); exit(EXIT_FAILURE); } syslog (LOG_INFO, "Here is the message: %s\n",buffer); pid_found = getProcessID((char *)buffer); sprintf(msg,"Monitoring process: %s (PID: %i)",buffer, pid_found); n = notify_notification_new ("notifmed",msg, NULL); notify_notification_set_timeout(n, notification_timeout * 1000); //3 seconds if (!notify_notification_show (n, NULL)) { g_error("Failed to send notification.\n"); return 1; } n = write(newsockfd,msg,255); if (n < 0) { syslog (LOG_ERR, "Error writing to the socket."); closelog(); close(newsockfd); close(sockfd); exit(EXIT_FAILURE); } //sleep(3); /* wait 3 seconds */ } close(newsockfd); close(sockfd); closelog(); exit(EXIT_SUCCESS); }
void svc(SYSTEM_CALL_DATA *SystemCallData) { MEMORY_MAPPED_IO mmio; short call_type; static short do_print = 10; INT32 Time; INT32 Status; short i; long* arg0=SystemCallData->Argument[0]; long* arg1=SystemCallData->Argument[1]; long* arg2=SystemCallData->Argument[2]; long* arg3=SystemCallData->Argument[3]; long* arg4=SystemCallData->Argument[4]; long *arg5=SystemCallData->Argument[5]; call_type = (short) SystemCallData->SystemCallNumber; if (do_print > 0) { printf("SVC handler: %s\n", call_names[call_type]); for (i = 0; i < SystemCallData->NumberOfArguments - 1; i++) { printf("Arg %d: Contents = (Decimal) %8ld, (Hex) %8lX\n", i, (unsigned long) SystemCallData->Argument[i], (unsigned long) SystemCallData->Argument[i]); } do_print--; } switch (call_type) { // Get time service call case SYSNUM_GET_TIME_OF_DAY: mmio.Mode = Z502ReturnValue; mmio.Field1 = mmio.Field2 = mmio.Field3 = 0; MEM_READ(Z502Clock, &mmio);//hardware call Time = mmio.Field1; (SystemCallData->Argument[0])=(long*)&Time; //statePrinter(call_type,arg0, arg1, arg2, arg3, arg4); break; // get the Timer start and generate idle. case SYSNUM_SLEEP: startTimer(arg0); //statePrinter(call_type,arg0, arg1, arg2, arg3, arg4); Dispatcher();//call dispatcher break; // create process case SYSNUM_CREATE_PROCESS: OSCreateProcess(arg0,arg1,arg2,arg3,arg4); //statePrinter(call_type,arg0, arg1, arg2, arg3, arg4); break; // get process id case SYSNUM_GET_PROCESS_ID: getProcessID(arg0,arg1,arg2); //statePrinter(call_type,arg0, arg1, arg2, arg3, arg4); break; // suspend process case SYSNUM_SUSPEND_PROCESS: suspendProcess(arg0, arg1); //statePrinter(call_type,arg0, arg1, arg2, arg3, arg4); break; // resume the process case SYSNUM_RESUME_PROCESS: resumeProcess(arg0, arg1); //statePrinter(call_type,arg0, arg1, arg2, arg3, arg4); break; // change priority; case SYSNUM_CHANGE_PRIORITY: changePriority(arg0,arg1,arg2); //statePrinter(call_type,arg0, arg1, arg2, arg3, arg4); break; // terminate system call case SYSNUM_TERMINATE_PROCESS: terminateSysProcess(arg0,arg1); break; case SYSNUM_SEND_MESSAGE: Send_message(arg0, arg1, arg2, arg3); break; case SYSNUM_RECEIVE_MESSAGE: ReceiveMessage(arg0, arg1, arg2, arg3, arg4, arg5); break; case SYSNUM_DISK_WRITE: DiskWrite(arg0, arg1, arg2); break; case SYSNUM_DISK_READ: DiskRead(arg0, arg1, arg2); break; case SYSNUM_DEFINE_SHARED_AREA: DefineSharedArea(arg0, arg1, arg2,arg3,arg4); break; default: printf( "ERROR! call_type not recognized!\n" ); printf( "Call_type is - %i\n", call_type); } } // End of svc
void getProcessInfo(const char * name, cgmProcessInfo * procInfo) { NTSTATUS rc = 0; DWORD len = MAX_PATH; ULONG retLen = 0; char * p= 0; char * start=0; // PROCESS_BASIC_INFORMATION pbInfo; // PEB pebInfo; // pfnNtQueryInformationProcess gNtQueryInformationProcess; // HMODULE hNtDll; // RTL_USER_PROCESS_PARAMETERS rtl; //UNICODE_STRING commandLine; //UNICODE_STRING imagePath; //WCHAR *commandLineContents; //WCHAR *imagePathContents; PROCESS_MEMORY_COUNTERS memoryCounters; HANDLE hProcess = NULL; DWORD werFault = 0; DWORD processID = 0; if (procInfo == NULL) { debug_log(LOG_ERR, "getProcessInfo(): Invalid procInfo handle."); return; } memset(procInfo, 0, sizeof(cgmProcessInfo)); werFault = getProcessID("WerFault.exe"); processID = getProcessID(name); procInfo->processID = processID; procInfo->werFaultID = werFault; if (procInfo->processID == 0) { debug_log(LOG_SVR, "getProcessInfo(): unable to find process: %s, processId: %d, werFault: %d", name, procInfo->processID, procInfo->werFaultID); return; } //hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID ); hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, processID ); if (hProcess != NULL) { strcpy_s(procInfo->szProcessName, sizeof(procInfo->szProcessName), name); // ----------------- // Get Handle Count. // ----------------- procInfo->handleCount = 0; rc = GetProcessHandleCount(hProcess, &procInfo->handleCount); if (rc == 0) { debug_log(LOG_ERR, "getProcessInfo(): unable to retrieve handle count for process: \'%s\', rc: %d", name, GetLastError()); procInfo->handleCount = 0; CloseHandle(hProcess); return; } // -------------------------------- // Get the size of the Working Set. // -------------------------------- procInfo->workingSetSize = 0; memset(&memoryCounters, 0, sizeof(memoryCounters)); rc = GetProcessMemoryInfo(hProcess, &memoryCounters, sizeof(memoryCounters)); if (rc == 0) { debug_log(LOG_ERR, "getProcessInfo(): unable to retrieve the size of the working set for process: \'%s\', rc: %d", name, GetLastError()); procInfo->workingSetSize = 0; CloseHandle(hProcess); return; } procInfo->workingSetSize = memoryCounters.WorkingSetSize; /* hNtDll = LoadLibrary(_T("ntdll.dll")); if (hNtDll == NULL) { debug_log("getProcessInfo(): Unable to load ntdll.dll"); CloseHandle(hProcess); return; } gNtQueryInformationProcess = (pfnNtQueryInformationProcess) GetProcAddress(hNtDll, "NtQueryInformationProcess"); if(gNtQueryInformationProcess == NULL) { debug_log("getProcessInfo(): NtQueryInformationProcess() call failed."); FreeLibrary(hNtDll); CloseHandle(hProcess); return ; } rc = gNtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbInfo, sizeof(pbInfo), &retLen); if(pbInfo.PebBaseAddress == NULL) { debug_log("getProcessInfo(): PEB address is null."); FreeLibrary(hNtDll); CloseHandle(hProcess); return; } // ------------------------------------------------------------------------------ // We need to read PEB of the process to find out the command line and full path. // ------------------------------------------------------------------------------ if(pbInfo.PebBaseAddress) { if(ReadProcessMemory(hProcess, pbInfo.PebBaseAddress, &pebInfo, sizeof(pebInfo) , NULL)) { if(ReadProcessMemory(hProcess, pebInfo.ProcessParameters, &rtl, sizeof(rtl) , NULL)) { rc = ReadProcessMemory(hProcess, &rtl.CommandLine, &commandLine, sizeof(commandLine), NULL); if(rc != 0 || (rc == 0 && GetLastError() == ERROR_PARTIAL_COPY)) { // allocate memory to hold the command line commandLineContents = (WCHAR *)malloc(rtl.CommandLine.Length); // read the command line if (!ReadProcessMemory(hProcess, rtl.CommandLine.Buffer, commandLineContents, rtl.CommandLine.Length, NULL)) { debug_log("getProcessInfo(): Could not read the command line string!"); free(commandLineContents); FreeLibrary(hNtDll); CloseHandle(hProcess); return ; } if (rtl.CommandLine.Length < sizeof(procInfo->szCmd)) wcstombs(procInfo->szCmd, commandLineContents, rtl.CommandLine.Length); free(commandLineContents); } else { debug_log("getProcessInfo(): Failed to read PEBs command line, rc: %d", GetLastError()); } rc = ReadProcessMemory(hProcess, &rtl.ImagePathName, &imagePath, sizeof(imagePath), NULL); if(rc != 0 || (rc == 0 && GetLastError() == ERROR_PARTIAL_COPY)) { // allocate memory to hold the image path imagePathContents = (WCHAR *)malloc(rtl.ImagePathName.Length); // read the path if (!ReadProcessMemory(hProcess, rtl.ImagePathName.Buffer, imagePathContents, rtl.ImagePathName.Length, NULL)) { debug_log("getProcessInfo(): Could not read the image path line string!"); free(imagePathContents); FreeLibrary(hNtDll); CloseHandle(hProcess); return ; } if (rtl.ImagePathName.Length < sizeof(procInfo->szImage)) wcstombs(procInfo->szImage, imagePathContents, rtl.ImagePathName.Length); free(imagePathContents); start = procInfo->szImage; p = strstr(procInfo->szImage, name); if (p != NULL) strncpy(procInfo->szCWD, start, p-start); } else { debug_log("getProcessInfo(): Failed to read PEBs image path line, rc: %d", GetLastError()); } } } } FreeLibrary(hNtDll); */ CloseHandle(hProcess); } else { debug_log(LOG_ERR, "getProcessInfo(): unable to open process: \'%s\', rc: %d", name, GetLastError()); return; } }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void ifb_printProcStatus (void) { int i, alive=0, dead=0; #if 0 FILE *fp; int state; char buff[MAXLINE]; char proc_usr[8], proc_stime[8], proc_tmptime[16]; int proc_pid; char cmd[] = "ps -ef|grep DAPP=|awk '{ print $1, $2, $5}'"; char *pos = NULL; int pos_idx=0; #endif if (displayQkeyFlag) { fprintf(stderr,"===================================================================================================\n"); fprintf(stderr," SYSTEM OPERATION MODE : %s\n", ifb_getSysOperMode(loc_sadb->loc_system_dup.myLocalDupStatus)); fprintf(stderr,"===================================================================================================\n"); fprintf(stderr," Process PID STATUS MSG_Q_KEY VERSION Process PID STATUS MSG_Q_KEY VERSION \n"); fprintf(stderr,"---------------------------------------------------------------------------------------------------"); } else { fprintf(stderr,"===================================================================================================\n"); fprintf(stderr," SYSTEM OPERATION MODE : %s\n", ifb_getSysOperMode(loc_sadb->loc_system_dup.myLocalDupStatus)); fprintf(stderr,"===================================================================================================\n"); fprintf(stderr," Process PID STATUS START-TIME VERSION Process PID STATUS START-TIME VERSION \n"); fprintf(stderr,"---------------------------------------------------------------------------------------------------"); } for (i=0; i<SYSCONF_MAX_APPL_NUM; i++) { if (!strcasecmp (confProcTbl[i].procName, "")) break; if (i%2==0) fprintf(stderr,"\n"); if (confProcTbl[i].runCnt) { if (displayQkeyFlag) { if (confProcTbl[i].runCnt == 1) fprintf(stderr," %-10s %-8d ALIVE 0x%-10x %-8s", confProcTbl[i].procName, (int)confProcTbl[i].pid, confProcTbl[i].msgQkey, confProcTbl[i].procVersion); else fprintf(stderr," %-10s %-8d ALIVE(%d)0x%-10x %-8s", confProcTbl[i].procName, (int)confProcTbl[i].pid, confProcTbl[i].runCnt, confProcTbl[i].msgQkey, confProcTbl[i].procVersion); } else { if (confProcTbl[i].runCnt == 1) fprintf(stderr," %-10s %-8d ALIVE %-12s %-8s", confProcTbl[i].procName, (int)confProcTbl[i].pid, confProcTbl[i].startTime, confProcTbl[i].procVersion); else fprintf(stderr," %-10s %-8d ALIVE(%d)%-12s %-8s", confProcTbl[i].procName, (int)confProcTbl[i].pid, confProcTbl[i].runCnt, confProcTbl[i].startTime, confProcTbl[i].procVersion); } alive += confProcTbl[i].runCnt; } else { if (displayQkeyFlag) { fprintf(stderr," %-10s - DEAD 0x%-10x %-8s", confProcTbl[i].procName, confProcTbl[i].msgQkey, confProcTbl[i].procVersion); } else { fprintf(stderr," %-10s - DEAD - - %-8s", confProcTbl[i].procName, "-"); } dead++; } } #if 1 /* SM/CM Process Status Management, by sjjeon */ { int sm_pid,cm_pid, rv; char startTM[32]; char version[]="R1.0.0"; // SM PID, TIME 을 구한다. sm_pid = getProcessID("SMSERVER"); rv = getPidInfo(sm_pid, startTM); if(rv >= 0){ fprintf(stderr,"\n %-10s %-8d ALIVE %-12s %-8s","SM",sm_pid, startTM, version); alive += 1; } else{ fprintf(stderr,"\n %-10s - DEAD - %-8s","SM", version); dead +=1; } // CM PID, TIME 을 구한다. memset(startTM,0x00,sizeof(startTM)); cm_pid = getProcessID("CM"); rv = getPidInfo(cm_pid, startTM); if(rv >= 0){ fprintf(stderr," %-10s %-8d ALIVE %-12s %-8s","CM",cm_pid, startTM, version); alive += 1; } else{ fprintf(stderr," %-10s - DEAD - %-8s","CM", version); dead +=1; } } #else /* SM/CM Process Status Management, by june */ fp = popen(cmd, "r"); if (fp == NULL) { perror("erro : "); exit(0); } fprintf(stderr,"\n"); while(fgets(buff, MAXLINE, fp) != NULL) { if( sscanf( &buff[0], "%s %d %s", proc_usr, &proc_pid, proc_tmptime)==3) { ////////////////////////////////////////////////////////////////////////////////////////////////// pos = strrchr(proc_tmptime, ':'); if (pos != NULL) { pos_idx = pos - proc_tmptime; proc_tmptime[pos_idx] = '\0'; } sprintf(proc_stime, "%s", proc_tmptime); ////////////////////////////////////////////////////////////////////////////////////////////////// if (!strncmp(proc_usr, "pcube", 5)) { strncpy(proc_stime, proc_tmptime, 5); if (smLiveCheck()==0) { fprintf(stderr," %-10s %-8d ALIVE %-5s %-8s", "SMSERVER", proc_pid, proc_stime, "R1.0.0"); alive++; } else { fprintf(stderr," %-10s %-8d DEAD %-5s %-8s", "SMSERVER", proc_pid, proc_stime, "R1.0.0"); dead++; } } if (!strncmp(proc_usr, "scmscm", 6)) { if (cmLiveCheck()==0) { fprintf(stderr," %-10s %-8d ALIVE %-5s %-8s", "CM", proc_pid, proc_stime, "R1.0.0"); alive++; } else { fprintf(stderr," %-10s %-8d DEAD %-5s %-8s", "CM", proc_pid, proc_stime, "R1.0.0"); dead++; } } } } state = pclose(fp); #endif fprintf(stderr,"\n===================================================================================================\n"); fprintf(stderr,"TOTAL:%d (ALIVE:%d, DEAD:%d)\n\n", alive+dead, alive, dead); return; } //----- End of ifb_printProcStatus -----//
void ReplicationCoordinatorExternalStateImpl::shardingOnTransitionToPrimaryHook( OperationContext* txn) { auto status = ShardingStateRecovery::recover(txn); if (ErrorCodes::isShutdownError(status.code())) { // Note: callers of this method don't expect exceptions, so throw only unexpected fatal // errors. return; } if (!status.isOK()) { fassertFailedWithStatus(40107, status); } if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) { status = Grid::get(txn)->catalogManager()->initializeConfigDatabaseIfNeeded(txn); if (!status.isOK() && status != ErrorCodes::AlreadyInitialized) { if (ErrorCodes::isShutdownError(status.code())) { // Don't fassert if we're mid-shutdown, let the shutdown happen gracefully. return; } fassertFailedWithStatus(40184, Status(status.code(), str::stream() << "Failed to initialize config database on config " "server's first transition to primary" << causedBy(status))); } if (status.isOK()) { // Load the clusterId into memory. Use local readConcern, since we can't use majority // readConcern in drain mode because the global lock prevents replication. This is // safe, since if the clusterId write is rolled back, any writes that depend on it will // also be rolled back. // Since we *just* wrote the cluster ID to the config.version document (via // ShardingCatalogManager::initializeConfigDatabaseIfNeeded), this should always // succeed. status = ClusterIdentityLoader::get(txn)->loadClusterId( txn, repl::ReadConcernLevel::kLocalReadConcern); if (ErrorCodes::isShutdownError(status.code())) { // Don't fassert if we're mid-shutdown, let the shutdown happen gracefully. return; } fassertStatusOK(40217, status); } // For upgrade from 3.2 to 3.4, check if any shards in config.shards are not yet marked as // shard aware, and attempt to initialize sharding awareness on them. auto shardAwareInitializationStatus = Grid::get(txn)->catalogManager()->initializeShardingAwarenessOnUnawareShards(txn); if (!shardAwareInitializationStatus.isOK()) { warning() << "Error while attempting to initialize sharding awareness on sharding " "unaware shards " << causedBy(shardAwareInitializationStatus); } // Free any leftover locks from previous instantiations auto distLockManager = Grid::get(txn)->catalogClient(txn)->getDistLockManager(); distLockManager->unlockAll(txn, distLockManager->getProcessID()); // If this is a config server node becoming a primary, start the balancer auto balancer = Balancer::get(txn); // We need to join the balancer here, because it might have been running at a previous time // when this node was a primary. balancer->joinThread(); balancer->startThread(txn); } else if (ShardingState::get(txn)->enabled()) { const auto configsvrConnStr = Grid::get(txn)->shardRegistry()->getConfigShard()->getConnString(); auto status = ShardingState::get(txn)->updateShardIdentityConfigString( txn, configsvrConnStr.toString()); if (!status.isOK()) { warning() << "error encountered while trying to update config connection string to " << configsvrConnStr << causedBy(status); } } // There is a slight chance that some stale metadata might have been loaded before the latest // optime has been recovered, so throw out everything that we have up to now ShardingState::get(txn)->clearCollectionMetadata(); }
void ReplicationCoordinatorExternalStateImpl::_shardingOnTransitionToPrimaryHook( OperationContext* opCtx) { auto status = ShardingStateRecovery::recover(opCtx); if (ErrorCodes::isShutdownError(status.code())) { // Note: callers of this method don't expect exceptions, so throw only unexpected fatal // errors. return; } fassertStatusOK(40107, status); if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) { status = ShardingCatalogManager::get(opCtx)->initializeConfigDatabaseIfNeeded(opCtx); if (!status.isOK() && status != ErrorCodes::AlreadyInitialized) { if (ErrorCodes::isShutdownError(status.code())) { // Don't fassert if we're mid-shutdown, let the shutdown happen gracefully. return; } fassertFailedWithStatus( 40184, status.withContext("Failed to initialize config database on config server's " "first transition to primary")); } if (status.isOK()) { // Load the clusterId into memory. Use local readConcern, since we can't use majority // readConcern in drain mode because the global lock prevents replication. This is // safe, since if the clusterId write is rolled back, any writes that depend on it will // also be rolled back. // Since we *just* wrote the cluster ID to the config.version document (via // ShardingCatalogManager::initializeConfigDatabaseIfNeeded), this should always // succeed. status = ClusterIdentityLoader::get(opCtx)->loadClusterId( opCtx, repl::ReadConcernLevel::kLocalReadConcern); if (ErrorCodes::isShutdownError(status.code())) { // Don't fassert if we're mid-shutdown, let the shutdown happen gracefully. return; } fassertStatusOK(40217, status); } // Free any leftover locks from previous instantiations. auto distLockManager = Grid::get(opCtx)->catalogClient()->getDistLockManager(); distLockManager->unlockAll(opCtx, distLockManager->getProcessID()); // If this is a config server node becoming a primary, start the balancer Balancer::get(opCtx)->initiateBalancer(opCtx); if (auto validator = LogicalTimeValidator::get(_service)) { validator->enableKeyGenerator(opCtx, true); } } else if (ShardingState::get(opCtx)->enabled()) { invariant(serverGlobalParams.clusterRole == ClusterRole::ShardServer); const auto configsvrConnStr = Grid::get(opCtx)->shardRegistry()->getConfigShard()->getConnString(); auto status = ShardingState::get(opCtx)->updateShardIdentityConfigString( opCtx, configsvrConnStr.toString()); if (!status.isOK()) { warning() << "error encountered while trying to update config connection string to " << configsvrConnStr << causedBy(status); } CatalogCacheLoader::get(_service).onStepUp(); ShardingState::get(_service)->initiateChunkSplitter(); } else { // unsharded if (auto validator = LogicalTimeValidator::get(_service)) { validator->enableKeyGenerator(opCtx, true); } } SessionCatalog::get(_service)->onStepUp(opCtx); }