51ak.blogs

51ak带你看MYSQL5.7源码1:main入口函数

 

博客迁移至:

 

https://www.dboop.com/

从事DBA工作多年

MYSQL源码也是头一次接触

尝试记录下自己看MYSQL5.7源码的历程

申明:个人Python编程很溜,但是C++还停在白痴水平,源码理解方面有点弱,如发现有错误的地方,轻喷

 

目录:

51ak带你看MYSQL5.7源码1:main入口函数 (2018-03-21)

51ak带你看MYSQL5.7源码2:编译现有的代码 (2018-03-22)

51ak带你看MYSQL5.7源码3:修改代码实现你的第一个Mysql版本 (2018-03-23)

51ak带你看MYSQL5.7源码4:实现SQL黑名单功能(2018-04-11)

 

 

 

 

去MYSQL官网下源码:https://dev.mysql.com/downloads/mysql/

选 SOURCE  CODE  

 

 下载解压。选VS code来查看,

用VS打开发现这些目录 ,根据了解到的目录结构说明,我们关注标红的两个目录,SQL是MYSQL的核心代码 ,STORGE里是各个存储引擎的代码

 

打开sql/main.cc 发现只有一个函数,引用了同级目录下的mysqld_main(int argc, char **argv); 

 

F12跟过去,到了msyqld.cc下的这个过程 ,这里就是整个SERVER进程 的入口

 

接下来就一个巨大的代码段,来启动MYSQLD进程 

我按个人的理解加了注释如下:

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
#ifdef _WIN32
int win_main(int argc, char **argv)
#else
int mysqld_main(int argc, char **argv)
#endif
{
  /*
    Perform basic thread library and malloc initialization,
    to be able to read defaults files and parse options.
  */
  my_progname= argv[0]; /*注: 记下mysql进程名*/
 
 
#ifndef _WIN32
#ifdef WITH_PERFSCHEMA_STORAGE_ENGINE
  pre_initialize_performance_schema();
#endif /*WITH_PERFSCHEMA_STORAGE_ENGINE */
  // For windows, my_init() is called from the win specific mysqld_main
  if (my_init())                 // init my_sys library & pthreads
  {
    sql_print_error("my_init() failed.");
    flush_error_log_messages();
    return 1;
  }
#endif /* _WIN32 */
 
  orig_argc= argc;
  orig_argv= argv;
  my_getopt_use_args_separator= TRUE;
  my_defaults_read_login_file= FALSE;
  /*注: 这里是去读配置文件里的启动项,读的时候还带入了argv ,应该是argv优行,*/
  if (load_defaults(MYSQL_CONFIG_NAME, load_default_groups, &argc, &argv))
  {
    flush_error_log_messages();
    return 1;
  }
  my_getopt_use_args_separator= FALSE;
  defaults_argc= argc;
  defaults_argv= argv;
  remaining_argc= argc;
  remaining_argv= argv;
 
  /* Must be initialized early for comparison of options name */
  system_charset_info= &my_charset_utf8_general_ci;
 
  /* Write mysys error messages to the error log. */
  local_message_hook= error_log_print;
 
  int ho_error;
 
#ifdef WITH_PERFSCHEMA_STORAGE_ENGINE
  /*
    Initialize the array of performance schema instrument configurations.
  */
  init_pfs_instrument_array();
#endif /* WITH_PERFSCHEMA_STORAGE_ENGINE */
 /*注: 这里跟过去发现还是在处理启动变量*/
  ho_error= handle_early_options();
 
#if !defined(_WIN32) && !defined(EMBEDDED_LIBRARY)
 
  if (opt_bootstrap && opt_daemonize)
  {
    fprintf(stderr, "Bootstrap and daemon options are incompatible.\n");
    exit(MYSQLD_ABORT_EXIT);
  }
 
  if (opt_daemonize && log_error_dest == disabled_my_option &&
      (isatty(STDOUT_FILENO) || isatty(STDERR_FILENO)))
  {
    fprintf(stderr, "Please enable --log-error option or set appropriate "
                    "redirections for standard output and/or standard error "
                    "in daemon mode.\n");
    exit(MYSQLD_ABORT_EXIT);
  }
 
  if (opt_daemonize)
  {
    if (chdir("/") < 0)
    {
      fprintf(stderr, "Cannot change to root director: %s\n",
                      strerror(errno));
      exit(MYSQLD_ABORT_EXIT);
    }
 
    if ((pipe_write_fd= mysqld::runtime::mysqld_daemonize()) < 0)
    {
      fprintf(stderr, "mysqld_daemonize failed \n");
      exit(MYSQLD_ABORT_EXIT);
    }
  }
#endif
 /*注: 还是在处理启动变量。。。*/
  init_sql_statement_names();
  sys_var_init();
  ulong requested_open_files;
  adjust_related_options(&requested_open_files);
 
#ifdef WITH_PERFSCHEMA_STORAGE_ENGINE
  if (ho_error == 0)
  {
    if (!opt_help && !opt_bootstrap)
    {
      /* Add sizing hints from the server sizing parameters. */
      pfs_param.m_hints.m_table_definition_cache= table_def_size;
      pfs_param.m_hints.m_table_open_cache= table_cache_size;
      pfs_param.m_hints.m_max_connections= max_connections;
      pfs_param.m_hints.m_open_files_limit= requested_open_files;
      pfs_param.m_hints.m_max_prepared_stmt_count= max_prepared_stmt_count;
 
      PSI_hook= initialize_performance_schema(&pfs_param);
      if (PSI_hook == NULL && pfs_param.m_enabled)
      {
        pfs_param.m_enabled= false;
        sql_print_warning("Performance schema disabled (reason: init failed).");
      }
    }
  }
#else
  /*
    Other provider of the instrumentation interface should
    initialize PSI_hook here:
    - HAVE_PSI_INTERFACE is for the instrumentation interface
    - WITH_PERFSCHEMA_STORAGE_ENGINE is for one implementation
      of the interface,
    but there could be alternate implementations, which is why
    these two defines are kept separate.
  */
#endif /* WITH_PERFSCHEMA_STORAGE_ENGINE */
 
#ifdef HAVE_PSI_INTERFACE
  /*
    Obtain the current performance schema instrumentation interface,
    if available.
  */
  if (PSI_hook)
  {
    PSI *psi_server= (PSI*) PSI_hook->get_interface(PSI_CURRENT_VERSION);
    if (likely(psi_server != NULL))
    {
      set_psi_server(psi_server);
 
      /*
        Now that we have parsed the command line arguments, and have initialized
        the performance schema itself, the next step is to register all the
        server instruments.
      */
      init_server_psi_keys();
      /* Instrument the main thread */
      PSI_thread *psi= PSI_THREAD_CALL(new_thread)(key_thread_main, NULL, 0);
      PSI_THREAD_CALL(set_thread_os_id)(psi);
      PSI_THREAD_CALL(set_thread)(psi);
 
      /*
        Now that some instrumentation is in place,
        recreate objects which were initialised early,
        so that they are instrumented as well.
      */
      my_thread_global_reinit();
    }
  }
#endif /* HAVE_PSI_INTERFACE */
 /*注: ERRLOG初始化*/
  init_error_log();
 
  /* Initialize audit interface globals. Audit plugins are inited later. */
  mysql_audit_initialize();
 
#ifndef EMBEDDED_LIBRARY
  Srv_session::module_init();
#endif
 
  /*
    Perform basic query log initialization. Should be called after
    MY_INIT, as it initializes mutexes.
  */
   /*注: QUERYLOG初始化*/
  query_logger.init();
 
  if (ho_error)
  {
    /*
      Parsing command line option failed,
      Since we don't have a workable remaining_argc/remaining_argv
      to continue the server initialization, this is as far as this
      code can go.
      This is the best effort to log meaningful messages:
      - messages will be printed to stderr, which is not redirected yet,
      - messages will be printed in the NT event log, for windows.
    */
    flush_error_log_messages();
    /*
      Not enough initializations for unireg_abort()
      Using exit() for windows.
    */
    exit (MYSQLD_ABORT_EXIT);
  }
 
  if (init_common_variables())
    unireg_abort(MYSQLD_ABORT_EXIT);        // Will do exit
 /*注: 系统信号初始化*/
  my_init_signals();
 
  size_t guardize= 0;
#ifndef _WIN32
  int retval= pthread_attr_getguardsize(&connection_attrib, &guardize);
  DBUG_ASSERT(retval == 0);
  if (retval != 0)
    guardize= my_thread_stack_size;
#endif
 
#if defined(__ia64__) || defined(__ia64)
  /*
    Peculiar things with ia64 platforms - it seems we only have half the
    stack size in reality, so we have to double it here
  */
  guardize= my_thread_stack_size;
#endif
 
  my_thread_attr_setstacksize(&connection_attrib,
                            my_thread_stack_size + guardize);
 
  {
    /* Retrieve used stack size;  Needed for checking stack overflows */
    size_t stack_size= 0;
    my_thread_attr_getstacksize(&connection_attrib, &stack_size);
 
    /* We must check if stack_size = 0 as Solaris 2.9 can return 0 here */
    if (stack_size && stack_size < (my_thread_stack_size + guardize))
    {
      sql_print_warning("Asked for %lu thread stack, but got %ld",
                        my_thread_stack_size + guardize, (long) stack_size);
#if defined(__ia64__) || defined(__ia64)
      my_thread_stack_size= stack_size / 2;
#else
      my_thread_stack_size= static_cast<ulong>(stack_size - guardize);
#endif
    }
  }
 
#ifndef DBUG_OFF
  test_lc_time_sz();
  srand(static_cast<uint>(time(NULL)));
#endif
 
#ifndef _WIN32
  if ((user_info= check_user(mysqld_user)))
  {
#if HAVE_CHOWN
    if (unlikely(opt_initialize))
    {
      /* need to change the owner of the freshly created data directory */
      MY_STAT stat;
      char errbuf[MYSYS_STRERROR_SIZE];
      bool must_chown= true;
 
      /* fetch the directory's owner */
      if (!my_stat(mysql_real_data_home, &stat, MYF(0)))
      {
        sql_print_information("Can't read data directory's stats (%d): %s."
                              "Assuming that it's not owned by the same user/group",
                              my_errno(),
                              my_strerror(errbuf, sizeof(errbuf), my_errno()));
      }
      /* Don't change it if it's already the same as SElinux stops this */
      else if(stat.st_uid == user_info->pw_uid &&
              stat.st_gid == user_info->pw_gid)
        must_chown= false;
 
      if (must_chown &&
          chown(mysql_real_data_home, user_info->pw_uid, user_info->pw_gid)
         )
      {
        sql_print_error("Can't change data directory owner to %s", mysqld_user);
        unireg_abort(1);
      }
    }
#endif
 
 
#if defined(HAVE_MLOCKALL) && defined(MCL_CURRENT)
    if (locked_in_memory) // getuid() == 0 here
      set_effective_user(user_info);
    else
#endif
      set_user(mysqld_user, user_info);
  }
#endif // !_WIN32
 
  /*
   initiate key migration if any one of the migration specific
   options are provided.
  */
   /*注: 这一段应该是跟迁移有关的,不是很懂*/
  if (opt_keyring_migration_source ||
      opt_keyring_migration_destination ||
      migrate_connect_options)
  {
    Migrate_keyring mk;
    if (mk.init(remaining_argc, remaining_argv,
                opt_keyring_migration_source,
                opt_keyring_migration_destination,
                opt_keyring_migration_user,
                opt_keyring_migration_host,
                opt_keyring_migration_password,
                opt_keyring_migration_socket,
                opt_keyring_migration_port))
    {
      sql_print_error(ER_DEFAULT(ER_KEYRING_MIGRATION_STATUS),
                      "failed");
      log_error_dest= "stderr";
      flush_error_log_messages();
      unireg_abort(MYSQLD_ABORT_EXIT);
    }
 
    if (mk.execute())
    {
      sql_print_error(ER_DEFAULT(ER_KEYRING_MIGRATION_STATUS),
                      "failed");
      log_error_dest= "stderr";
      flush_error_log_messages();
      unireg_abort(MYSQLD_ABORT_EXIT);
    }
 
    sql_print_information(ER_DEFAULT(ER_KEYRING_MIGRATION_STATUS),
                          "successfull");
    log_error_dest= "stderr";
    flush_error_log_messages();
    unireg_abort(MYSQLD_SUCCESS_EXIT);
  }
 
  /*
   We have enough space for fiddling with the argv, continue
  */
  /*注:设置DATA变量*/
  if (my_setwd(mysql_real_data_home,MYF(MY_WME)) && !opt_help)
  {
    sql_print_error("failed to set datadir to %s", mysql_real_data_home);
    unireg_abort(MYSQLD_ABORT_EXIT);        /* purecov: inspected */
  }
  /*注:设置BINLOG*/
  //If the binlog is enabled, one needs to provide a server-id
  if (opt_bin_log && !(server_id_supplied) )
  {
    sql_print_error("You have enabled the binary log, but you haven't provided "
                    "the mandatory server-id. Please refer to the proper "
                    "server start-up parameters documentation");
    unireg_abort(MYSQLD_ABORT_EXIT);
  }
 
  /*
   The subsequent calls may take a long time : e.g. innodb log read.
   Thus set the long running service control manager timeout
  */
#if defined(_WIN32)
  Service.SetSlowStarting(slow_start_timeout);
#endif
  /*注:这个很重要。核心模块在这里启动了*/
  if (init_server_components())
    unireg_abort(MYSQLD_ABORT_EXIT);
 
  /*
    Each server should have one UUID. We will create it automatically, if it
    does not exist.
   */
  if (init_server_auto_options())
  {
    sql_print_error("Initialization of the server's UUID failed because it could"
                    " not be read from the auto.cnf file. If this is a new"
                    " server, the initialization failed because it was not"
                    " possible to generate a new UUID.");
    unireg_abort(MYSQLD_ABORT_EXIT);
  }
 
  /*注:下面这段跟SID有关*/
  /*
    Add server_uuid to the sid_map.  This must be done after
    server_uuid has been initialized in init_server_auto_options and
    after the binary log (and sid_map file) has been initialized in
    init_server_components().
 
    No error message is needed: init_sid_map() prints a message.
 
    Strictly speaking, this is not currently needed when
    opt_bin_log==0, since the variables that gtid_state->init
    initializes are not currently used in that case.  But we call it
    regardless to avoid possible future bugs if gtid_state ever
    needs to do anything else.
  */
  global_sid_lock->wrlock();
  int gtid_ret= gtid_state->init();
  global_sid_lock->unlock();
 
  if (gtid_ret)
    unireg_abort(MYSQLD_ABORT_EXIT);
 
  // Initialize executed_gtids from mysql.gtid_executed table.
  if (gtid_state->read_gtid_executed_from_table() == -1)
    unireg_abort(1);
 
  if (opt_bin_log)
  {
    /*
      Initialize GLOBAL.GTID_EXECUTED and GLOBAL.GTID_PURGED from
      gtid_executed table and binlog files during server startup.
    */
    Gtid_set *executed_gtids=
      const_cast<Gtid_set *>(gtid_state->get_executed_gtids());
    Gtid_set *lost_gtids=
      const_cast<Gtid_set *>(gtid_state->get_lost_gtids());
    Gtid_set *gtids_only_in_table=
      const_cast<Gtid_set *>(gtid_state->get_gtids_only_in_table());
    Gtid_set *previous_gtids_logged=
      const_cast<Gtid_set *>(gtid_state->get_previous_gtids_logged());
 
    Gtid_set purged_gtids_from_binlog(global_sid_map, global_sid_lock);
    Gtid_set gtids_in_binlog(global_sid_map, global_sid_lock);
    Gtid_set gtids_in_binlog_not_in_table(global_sid_map, global_sid_lock);
 
    if (mysql_bin_log.init_gtid_sets(&gtids_in_binlog,
                                     &purged_gtids_from_binlog,
                                     opt_master_verify_checksum,
                                     true/*true=need lock*/,
                                     NULL/*trx_parser*/,
                                     NULL/*gtid_partial_trx*/,
                                     true/*is_server_starting*/))
      unireg_abort(MYSQLD_ABORT_EXIT);
 
    global_sid_lock->wrlock();
 
    purged_gtids_from_binlog.dbug_print("purged_gtids_from_binlog");
    gtids_in_binlog.dbug_print("gtids_in_binlog");
 
    if (!gtids_in_binlog.is_empty() &&
        !gtids_in_binlog.is_subset(executed_gtids))
    {
      gtids_in_binlog_not_in_table.add_gtid_set(&gtids_in_binlog);
      if (!executed_gtids->is_empty())
        gtids_in_binlog_not_in_table.remove_gtid_set(executed_gtids);
      /*
        Save unsaved GTIDs into gtid_executed table, in the following
        four cases:
          1. the upgrade case.
          2. the case that a slave is provisioned from a backup of
             the master and the slave is cleaned by RESET MASTER
             and RESET SLAVE before this.
          3. the case that no binlog rotation happened from the
             last RESET MASTER on the server before it crashes.
          4. The set of GTIDs of the last binlog is not saved into the
             gtid_executed table if server crashes, so we save it into
             gtid_executed table and executed_gtids during recovery
             from the crash.
      */
      if (gtid_state->save(&gtids_in_binlog_not_in_table) == -1)
      {
        global_sid_lock->unlock();
        unireg_abort(MYSQLD_ABORT_EXIT);
      }
      executed_gtids->add_gtid_set(&gtids_in_binlog_not_in_table);
    }
 
    /* gtids_only_in_table= executed_gtids - gtids_in_binlog */
    if (gtids_only_in_table->add_gtid_set(executed_gtids) !=
        RETURN_STATUS_OK)
    {
      global_sid_lock->unlock();
      unireg_abort(MYSQLD_ABORT_EXIT);
    }
    gtids_only_in_table->remove_gtid_set(&gtids_in_binlog);
    /*
      lost_gtids = executed_gtids -
                   (gtids_in_binlog - purged_gtids_from_binlog)
                 = gtids_only_in_table + purged_gtids_from_binlog;
    */
    DBUG_ASSERT(lost_gtids->is_empty());
    if (lost_gtids->add_gtid_set(gtids_only_in_table) != RETURN_STATUS_OK ||
        lost_gtids->add_gtid_set(&purged_gtids_from_binlog) !=
        RETURN_STATUS_OK)
    {
      global_sid_lock->unlock();
      unireg_abort(MYSQLD_ABORT_EXIT);
    }
 
    /* Prepare previous_gtids_logged for next binlog */
    if (previous_gtids_logged->add_gtid_set(&gtids_in_binlog) !=
        RETURN_STATUS_OK)
    {
      global_sid_lock->unlock();
      unireg_abort(MYSQLD_ABORT_EXIT);
    }
 
    /*
      Write the previous set of gtids at this point because during
      the creation of the binary log this is not done as we cannot
      move the init_gtid_sets() to a place before openning the binary
      log. This requires some investigation.
 
      /Alfranio
    */
    Previous_gtids_log_event prev_gtids_ev(&gtids_in_binlog);
 
    global_sid_lock->unlock();
 
    (prev_gtids_ev.common_footer)->checksum_alg=
      static_cast<enum_binlog_checksum_alg>(binlog_checksum_options);
 
    if (prev_gtids_ev.write(mysql_bin_log.get_log_file()))
      unireg_abort(MYSQLD_ABORT_EXIT);
    mysql_bin_log.add_bytes_written(
      prev_gtids_ev.common_header->data_written);
 
    if (flush_io_cache(mysql_bin_log.get_log_file()) ||
        mysql_file_sync(mysql_bin_log.get_log_file()->file, MYF(MY_WME)))
      unireg_abort(MYSQLD_ABORT_EXIT);
    mysql_bin_log.update_binlog_end_pos();
 
    (void) RUN_HOOK(server_state, after_engine_recovery, (NULL));
  }
 
  /*注: 网络相关的初始化*/
  if (init_ssl())
    unireg_abort(MYSQLD_ABORT_EXIT);
  if (network_init())
    unireg_abort(MYSQLD_ABORT_EXIT);
 
#ifdef _WIN32
#ifndef EMBEDDED_LIBRARY
  if (opt_require_secure_transport &&
      !opt_enable_shared_memory && !opt_use_ssl &&
      !opt_initialize && !opt_bootstrap)
  {
    sql_print_error("Server is started with --require-secure-transport=ON "
                    "but no secure transports (SSL or Shared Memory) are "
                    "configured.");
    unireg_abort(MYSQLD_ABORT_EXIT);
  }
#endif
 
#endif
 
  /*
   Initialize my_str_malloc(), my_str_realloc() and my_str_free()
  */
  my_str_malloc= &my_str_malloc_mysqld;
  my_str_free= &my_str_free_mysqld;
  my_str_realloc= &my_str_realloc_mysqld;
 
  error_handler_hook= my_message_sql;
 
  /* Save pid of this process in a file */
  if (!opt_bootstrap)
    create_pid_file();
 
 
  /* Read the optimizer cost model configuration tables */
  if (!opt_bootstrap)
    reload_optimizer_cost_constants();
 
  if (mysql_rm_tmp_tables() || acl_init(opt_noacl) ||
      my_tz_init((THD *)0, default_tz_name, opt_bootstrap) ||
      grant_init(opt_noacl))
  {
    abort_loop= true;
 
    delete_pid_file(MYF(MY_WME));
 
    unireg_abort(MYSQLD_ABORT_EXIT);
  }
 
  if (!opt_bootstrap)
    servers_init(0);
 
  if (!opt_noacl)
  {
#ifdef HAVE_DLOPEN
    udf_init();
#endif
  }
 
  /*注:设置SHOW STATUS时的变量*/
  init_status_vars();
  /* If running with bootstrap, do not start replication. */
  if (opt_bootstrap)
    opt_skip_slave_start= 1;
 
  /*注:初始化BINLOG的值了*/
  check_binlog_cache_size(NULL);
  check_binlog_stmt_cache_size(NULL);
 
  binlog_unsafe_map_init();
 
  /* If running with bootstrap, do not start replication. */
  if (!opt_bootstrap)
  {
    // Make @@slave_skip_errors show the nice human-readable value.
    set_slave_skip_errors(&opt_slave_skip_errors);
 
    /*
      init_slave() must be called after the thread keys are created.
    */
    if (server_id != 0)
      init_slave(); /* Ignoring errors while configuring replication. */
  }
 
#ifdef WITH_PERFSCHEMA_STORAGE_ENGINE
  initialize_performance_schema_acl(opt_bootstrap);
  /*
    Do not check the structure of the performance schema tables
    during bootstrap:
    - the tables are not supposed to exist yet, bootstrap will create them
    - a check would print spurious error messages
  */
  if (! opt_bootstrap)
    check_performance_schema();
#endif
 
  initialize_information_schema_acl();
 
  execute_ddl_log_recovery();
  (void) RUN_HOOK(server_state, after_recovery, (NULL));
 
  if (Events::init(opt_noacl || opt_bootstrap))
    unireg_abort(MYSQLD_ABORT_EXIT);
 
#ifndef _WIN32
  //  Start signal handler thread.
  start_signal_handler();
#endif
 
  /*注:启动了*/
  if (opt_bootstrap)
  {
    start_processing_signals();
 
    int error= bootstrap(mysql_stdin);
    unireg_abort(error ? MYSQLD_ABORT_EXIT : MYSQLD_SUCCESS_EXIT);
  }
 
  if (opt_init_file && *opt_init_file)
  {
    if (read_init_file(opt_init_file))
      unireg_abort(MYSQLD_ABORT_EXIT);
  }
 
  /*
    Event must be invoked after error_handler_hook is assigned to
    my_message_sql, otherwise my_message will not cause the event to abort.
  */
  if (mysql_audit_notify(AUDIT_EVENT(MYSQL_AUDIT_SERVER_STARTUP_STARTUP),
                         (const char **) argv, argc))
    unireg_abort(MYSQLD_ABORT_EXIT);
 
#ifdef _WIN32
  create_shutdown_thread();
#endif
  start_handle_manager();
 
  create_compress_gtid_table_thread();
 
  sql_print_information(ER_DEFAULT(ER_STARTUP),
                        my_progname,
                        server_version,
#ifdef HAVE_SYS_UN_H
                        (opt_bootstrap ? (char*) "" : mysqld_unix_port),
#else
                        (char*) "",
#endif
                         mysqld_port,
                         MYSQL_COMPILATION_COMMENT);
#if defined(_WIN32)
  Service.SetRunning();
#endif
 
  start_processing_signals();
 
#ifdef WITH_NDBCLUSTER_STORAGE_ENGINE
  /* engine specific hook, to be made generic */
  if (ndb_wait_setup_func && ndb_wait_setup_func(opt_ndb_wait_setup))
  {
    sql_print_warning("NDB : Tables not available after %lu seconds."
                      "  Consider increasing --ndb-wait-setup value",
                      opt_ndb_wait_setup);
  }
#endif
 
  if (!opt_bootstrap)
  {
    /*
      Execute an I_S query to implicitly check for tables using the deprecated
      partition engine. No need to do this during bootstrap. We ignore the
      return value from the query execution. Note that this must be done after
      NDB is initialized to avoid polluting the server with invalid table shares.
    */
    if (!opt_disable_partition_check)
    {
      sql_print_information(
              "Executing 'SELECT * FROM INFORMATION_SCHEMA.TABLES;' "
              "to get a list of tables using the deprecated partition "
              "engine.");
 
      sql_print_information("Beginning of list of non-natively partitioned tables");
      (void) bootstrap_single_query(
              "SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES "
              "WHERE CREATE_OPTIONS LIKE '%partitioned%';");
      sql_print_information("End of list of non-natively partitioned tables");
    }
  }
 
  /*
    Set opt_super_readonly here because if opt_super_readonly is set
    in get_option, it will create problem while setting up event scheduler.
  */
  set_super_read_only_post_init();
 
  DBUG_PRINT("info", ("Block, listening for incoming connections"));
 
  (void)MYSQL_SET_STAGE(0 ,__FILE__, __LINE__);
 
  server_operational_state= SERVER_OPERATING;
 
  (void) RUN_HOOK(server_state, before_handle_connection, (NULL));
 
  /*注:设置连接池*/
#if defined(_WIN32)
  setup_conn_event_handler_threads();
#else
  mysql_mutex_lock(&LOCK_socket_listener_active);
  // Make it possible for the signal handler to kill the listener.
  socket_listener_active= true;
  mysql_mutex_unlock(&LOCK_socket_listener_active);
 
  if (opt_daemonize)
    mysqld::runtime::signal_parent(pipe_write_fd,1);
 
  mysqld_socket_acceptor->connection_event_loop();
#endif /* _WIN32 */
  server_operational_state= SERVER_SHUTTING_DOWN;
 
  DBUG_PRINT("info", ("No longer listening for incoming connections"));
 
  mysql_audit_notify(MYSQL_AUDIT_SERVER_SHUTDOWN_SHUTDOWN,
                     MYSQL_AUDIT_SERVER_SHUTDOWN_REASON_SHUTDOWN,
                     MYSQLD_SUCCESS_EXIT);
 
  terminate_compress_gtid_table_thread();
  /*
    Save set of GTIDs of the last binlog into gtid_executed table
    on server shutdown.
  */
  if (opt_bin_log)
    if (gtid_state->save_gtids_of_last_binlog_into_table(false))
      sql_print_warning("Failed to save the set of Global Transaction "
                        "Identifiers of the last binary log into the "
                        "mysql.gtid_executed table while the server was "
                        "shutting down. The next server restart will make "
                        "another attempt to save Global Transaction "
                        "Identifiers into the table.");
 
#ifndef _WIN32
  mysql_mutex_lock(&LOCK_socket_listener_active);
  // Notify the signal handler that we have stopped listening for connections.
  socket_listener_active= false;
  mysql_cond_broadcast(&COND_socket_listener_active);
  mysql_mutex_unlock(&LOCK_socket_listener_active);
#endif // !_WIN32
 
#ifdef HAVE_PSI_THREAD_INTERFACE
  /*
    Disable the main thread instrumentation,
    to avoid recording events during the shutdown.
  */
  PSI_THREAD_CALL(delete_current_thread)();
#endif
 
  DBUG_PRINT("info", ("Waiting for shutdown proceed"));
  int ret= 0;
#ifdef _WIN32
  if (shutdown_thr_handle.handle)
    ret= my_thread_join(&shutdown_thr_handle, NULL);
  shutdown_thr_handle.handle= NULL;
  if (0 != ret)
    sql_print_warning("Could not join shutdown thread. error:%d", ret);
#else
  if (signal_thread_id.thread != 0)
    ret= my_thread_join(&signal_thread_id, NULL);
  signal_thread_id.thread= 0;
  if (0 != ret)
    sql_print_warning("Could not join signal_thread. error:%d", ret);
#endif
  /*注:请理退出*/
  clean_up(1);
  mysqld_exit(MYSQLD_SUCCESS_EXIT);
}

  

好了,第一天,只看这一节代码就够了

 

posted on   51ak  阅读(2749)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!

导航

统计

点击右上角即可分享
微信分享提示