Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / common / code_environment.cc
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3 /*
4  * Ceph - scalable distributed file system
5  *
6  * Copyright (C) 2011 New Dream Network
7  *
8  * This is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License version 2.1, as published by the Free Software
11  * Foundation.  See file COPYING.
12  *
13  */
14
15 #include "common/code_environment.h"
16
17 #include <iostream>
18
19 #ifdef HAVE_SYS_PRCTL_H
20 #include <sys/prctl.h>
21 #endif
22
23 code_environment_t g_code_env = CODE_ENVIRONMENT_UTILITY;
24
25 extern "C" const char *code_environment_to_str(enum code_environment_t e)
26 {
27   switch (e) {
28     case CODE_ENVIRONMENT_UTILITY:
29       return "CODE_ENVIRONMENT_UTILITY";
30     case CODE_ENVIRONMENT_DAEMON:
31       return "CODE_ENVIRONMENT_DAEMON";
32     case CODE_ENVIRONMENT_LIBRARY:
33       return "CODE_ENVIRONMENT_LIBRARY";
34     default:
35       return NULL;
36   }
37 }
38
39 std::ostream &operator<<(std::ostream &oss, const enum code_environment_t e)
40 {
41   oss << code_environment_to_str(e);
42   return oss;
43 }
44
45 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_GET_NAME) /* Since 2.6.11 */
46
47 int get_process_name(char *buf, int len)
48 {
49   if (len <= 16) {
50     /* The man page discourages using this prctl with a buffer shorter
51      * than 16 bytes. With a 16-byte buffer, it might not be
52      * null-terminated. */
53     return -ENAMETOOLONG;
54   }
55   memset(buf, 0, len);
56   return prctl(PR_GET_NAME, buf);
57 }
58
59 #elif defined(HAVE_GETPROGNAME)
60
61 int get_process_name(char *buf, int len)
62 {
63   if (len <= 0) {
64     return -EINVAL;
65   }
66
67   const char *progname = getprogname();
68   if (progname == nullptr || *progname == '\0') {
69     return -ENOSYS;
70   }
71
72   strncpy(buf, progname, len - 1);
73   buf[len - 1] = '\0';
74   return 0;
75 }
76
77 #else
78
79 int get_process_name(char *buf, int len)
80 {
81   return -ENOSYS;
82 }
83
84 #endif
85
86 std::string get_process_name_cpp()
87 {
88   char buf[32];
89   if (get_process_name(buf, sizeof(buf))) {
90     return "(unknown)";
91   }
92   return std::string(buf);
93 }