gcontini
2020-01-09 b6277b30756c96404bc747f32ae45e9d3e205447
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
/*
 * virtualization.cpp
 *
 *  Created on: Dec 15, 2019
 *      Author: GC
 */
#include <paths.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <sys/utsname.h>
 
#include "../../base/base.h"
#include "../cpu_info.hpp"
#include "../execution_environment.hpp"
 
namespace license {
 
// 0=NO 1=Docker/2=Lxc
static int checkContainerProc() {
    // in docer /proc/self/cgroups contains the "docker" or "lxc" string
    // https://stackoverflow.com/questions/23513045/how-to-check-if-a-process-is-running-inside-docker-container
    char path[MAX_PATH] = {0};
    char proc_path[MAX_PATH], pidStr[64];
    pid_t pid = getpid();
    sprintf(pidStr, "%d", pid);
    strcpy(proc_path, "/proc/");
    strcat(proc_path, pidStr);
    strcat(proc_path, "/cgroup");
 
    FILE *fp;
    char *line = NULL;
    size_t len = 0;
    ssize_t read;
    int result = 0;
 
    fp = fopen(proc_path, "r");
    if (fp == NULL) {
        return 0;
    }
 
    while ((read = getline(&line, &len, fp)) != -1 && result == 0) {
        // line[len]=0;
        // printf("Retrieved line of length %zu:\n", read);
        // printf("%s", line);
        if (strstr(line, "docker") != NULL) {
            result = 1;
        }
        if (strstr(line, "lxc") != NULL) {
            result = 2;
        }
    }
 
    fclose(fp);
    if (line) free(line);
    return result;
}
 
// 0=NO 1=Docker/Lxc
static int checkLXC() { return (access("/var/run/systemd/container", F_OK) == 0) ? 1 : 0; }
 
VIRTUALIZATION ExecutionEnvironment::getVirtualization() {
    VIRTUALIZATION result = NONE;
    CpuInfo cpuInfo;
    int isContainer = checkContainerProc();
    if (isContainer == 1) {
        result = CONTAINER;
    } else if (isContainer == 2 || checkLXC()) {
        result = CONTAINER;
    } else if (cpuInfo.cpu_virtual()) {
        result = VM;
    } else {
    }
    return result;
}
}  // namespace license