config.c 1.7 KB
Newer Older
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
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void addrToString(const char *host, uint16_t port, char *addr, int len) { snprintf(addr, len, "%s:%hu", host, port); }

void parseAddr(const char *addr, char *host, int len, uint16_t *port) {
  char *tmp = (char *)malloc(strlen(addr) + 1);
  strcpy(tmp, addr);

  char *context;
  char *separator = ":";
  char *token = strtok_r(tmp, separator, &context);
  if (token) {
    snprintf(host, len, "%s", token);
  }

  token = strtok_r(NULL, separator, &context);
  if (token) {
    sscanf(token, "%hu", port);
  }

  free(tmp);
}

int parseConf(int argc, char **argv, RaftServerConfig *pConf) {
  memset(pConf, 0, sizeof(*pConf));

  int option_index, option_value;
  option_index = 0;
  static struct option long_options[] = {{"help", no_argument, NULL, 'h'},
                                         {"addr", required_argument, NULL, 'a'},
                                         {"dir", required_argument, NULL, 'd'},
                                         {NULL, 0, NULL, 0}};

  while ((option_value = getopt_long(argc, argv, "ha:d:", long_options, &option_index)) != -1) {
    switch (option_value) {
      case 'a': {
        parseAddr(optarg, pConf->me.host, sizeof(pConf->me.host), &pConf->me.port);
        break;
      }

      case 'd': {
        snprintf(pConf->baseDir, sizeof(pConf->baseDir), "%s", optarg);
        break;
      }

      case 'h': {
        return -2;
      }

      default: { return -2; }
    }
  }

  return 0;
}

void printConf(RaftServerConfig *pConf) {
  printf("\n---printConf: \n");
  printf("me: [%s:%hu] \n", pConf->me.host, pConf->me.port);
  printf("dataDir: [%s] \n\n", pConf->baseDir);
}