File size: 8,364 Bytes
e1191aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/*
 *  STaRS, Scalable Task Routing approach to distributed Scheduling
 *  Copyright (C) 2012 Javier Celaya
 *
 *  This file is part of STaRS.
 *
 *  STaRS is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  STaRS is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with STaRS; if not, see <http://www.gnu.org/licenses/>.
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <csignal>
#include <sstream>
#include <iostream>
#include <fstream>
#include <list>
#include <map>
#include <string>
#include <boost/thread.hpp>
#include <boost/thread/condition.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost;
namespace fs = boost::filesystem;


unsigned long int getAvailableMemory() {
    unsigned long int free;
    unsigned long int total;
    string dummy;
    ifstream file("/proc/meminfo");
    file >> dummy >> total;
    file.ignore(1000, '\n');
    file >> dummy >> free;
    return (free - total / 10) >> 10;   // Approx 90% of total memory
}


class Simulations {
public:
    static Simulations & getInstance() {
        static Simulations s;
        return s;
    }

    void parseCmdLine(int argc, char * argv[]);
    int run(int argc, char * argv[]);
    void stop();
    void getNewCases();
    void waitProcesses();

    pid_t spawnProcess(const map<string, string> & properties);
    unsigned long int getMemoryLimit(const map<string, string> & properties) const {
        unsigned long int mem = 0;
        auto it = properties.find("max_mem");
        if (it != properties.end())
            istringstream(it->second) >> mem;
        return mem;
    }
    void reschedule();

private:
    list<map<string, string> > caseInstances;
    bool end, waitOnPipe;
    unsigned int numProcesses;
    unsigned long int availableMemory;
    list<pair<pid_t, unsigned long int> > processes;
    string simExec, pipeName;
    thread pipeThread, waitThread;
    mutex m;            ///< Mutex to put and get queue messages.
    condition newCasesOrProcesses;     ///< Barrier to wait for a message
    condition children;     ///< Barrier to wait for children

    Simulations() : end(false), waitOnPipe(false), numProcesses(1), availableMemory(getAvailableMemory()), pipeName("sweeperpipe") {}
};


void getPropertiesList(const string & fileName, std::list<std::map<std::string, std::string> > & combinations);


void finish(int param) {
    Simulations::getInstance().stop();
}


int main(int argc, char * argv[]) {
    return Simulations::getInstance().run(argc, argv);
}


void Simulations::parseCmdLine(int argc, char * argv[]) {
    for (int i = 1; i < argc; i++) {
        if (argv[i] == string("-f") && ++i < argc)
            pipeName = argv[i];
        else if (argv[i] == string("-e") && ++i < argc)
            simExec = argv[i];
        else if (argv[i] == string("-p") && ++i < argc)
            istringstream(argv[i]) >> numProcesses;
        else if (argv[i] == string("-m") && ++i < argc)
            istringstream(argv[i]) >> availableMemory;
    }
}


void Simulations::getNewCases() {
    while (true) {
        list<map<string, string> > newInstances;
        getPropertiesList(pipeName, newInstances);
        this_thread::interruption_point();
        if (newInstances.empty()) continue;
        cout << "Adding " << newInstances.size() << " more cases." << endl;
        {
            mutex::scoped_lock lock(m);
            caseInstances.splice(caseInstances.end(), newInstances);
        }
        newCasesOrProcesses.notify_all();
    }
}


void Simulations::waitProcesses() {
    while (true) {
        {
            mutex::scoped_lock lock(m);
            if (processes.empty()) {
                if (end)
                    return;
                children.wait(lock);
                if (end)
                    return;
            }
        }
        pid_t pid = wait(NULL);
        if (pid != -1) {
            cout << "Process " << pid << " ended." << endl;
            {
                mutex::scoped_lock lock(m);
                for (auto it = processes.begin(); it != processes.end(); ++it) {
                    if (it->first == pid) {
                        availableMemory += it->second;
                        processes.erase(it);
                        break;
                    }
                }
            }
            newCasesOrProcesses.notify_all();
        }
    }
}


int Simulations::run(int argc, char * argv[]) {
    signal(SIGTERM, finish);
    signal(SIGINT, finish);

    parseCmdLine(argc, argv);
    if (simExec == "") {
        cerr << "Usage: " << argv[0] << " -e sim_program [-f pipe_name] [-p num_processes] [-m max_memory]" << endl;
        return 1;
    }
    cout << "Using " << numProcesses << " processors and " << availableMemory << " megabytes of memory." << endl;

    if (fs::exists(pipeName) && fs::is_regular_file(pipeName)) {
        cout << "Reading configuration from " << pipeName << endl;
        getPropertiesList(pipeName, caseInstances);
        waitOnPipe = false;
    } else {
        mknod(pipeName.c_str(), S_IFIFO | 0600, 0);
        cout << "Listening on " << pipeName << endl;
        pipeThread = thread(bind(&Simulations::getNewCases, this));
        waitOnPipe = true;
    }

    waitThread = thread(bind(&Simulations::waitProcesses, this));

    do {
        mutex::scoped_lock lock(m);
        reschedule();
        if (!waitOnPipe && caseInstances.empty()) {
            end = true;
        } else {
            if (processes.empty() && waitOnPipe) {
                cout << "Waiting for tests..." << endl;
            }
            newCasesOrProcesses.wait(lock);
        }
    } while (!end);

    pipeThread.join();
    waitThread.join();
    return 0;
}


void Simulations::reschedule() {
    // Schedule as many cases as possible until memory is full
    auto instance = caseInstances.begin();
    while (processes.size() < numProcesses && instance != caseInstances.end()) {
        // Try to launch this case
        unsigned long int mem = getMemoryLimit(*instance);
        if (mem <= availableMemory) {
            pid_t pid = spawnProcess(*instance);
            availableMemory -= mem;
            processes.push_back(make_pair(pid, mem));
            children.notify_all();
            instance = caseInstances.erase(instance);
        }
        else {
            if (processes.empty()) {
                cout << "Unable to run simulation, not enough memory." << endl;
                instance = caseInstances.erase(instance);
            } else ++instance;
        }
    }
}


pid_t Simulations::spawnProcess(const map<string, string> & properties) {
    // Redirect stdio
    int fd[2];
    pipe(fd);
    pid_t pid;
    if ((pid = fork())) {
        // Close read end
        close(fd[0]);
        // Feed configuration through write end
        ostringstream oss;
        for (auto & i : properties) {
            oss << i.first << "=" << i.second << endl;
        }
        write(fd[1], oss.str().c_str(), oss.tellp());
        close(fd[1]);
        return pid;
    } else {
        // Close write end
        close(fd[1]);
        // Set read end as standard input
        dup2(fd[0], 0);
        execl(simExec.c_str(), simExec.c_str(), "-", NULL);
        // This function only returns on error
        cout << "Error running simulation." << endl;
        close(fd[0]);
        exit(1);
    }
}


void Simulations::stop() {
    end = true;
    pipeThread.interrupt();
    //waitThread.interrupt();
    cout << "Stopping current processes." << endl;
    for (list<pair<pid_t, unsigned long int> >::iterator it = processes.begin(); it != processes.end(); it++)
        kill(it->first, SIGTERM);
    children.notify_all();
    // Signal end of file in the pipe
    ofstream(pipeName.c_str(), ios::out | ios::app).close();
    newCasesOrProcesses.notify_all();
}