This repository has been archived by the owner on Jul 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 218
/
DaemonOperation.java
277 lines (225 loc) · 8.6 KB
/
DaemonOperation.java
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
/*
* Syncany, www.syncany.org
* Copyright (C) 2011-2014 Philipp C. Heckel <philipp.heckel@gmail.com>
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.syncany.operations.daemon;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.syncany.config.Config;
import org.syncany.config.ConfigException;
import org.syncany.config.UserConfig;
import org.syncany.config.to.DaemonConfigTO;
import org.syncany.config.to.FolderTO;
import org.syncany.config.to.PortTO;
import org.syncany.config.to.UserTO;
import org.syncany.crypto.CipherUtil;
import org.syncany.operations.Operation;
import org.syncany.operations.OperationResult;
import org.syncany.operations.daemon.ControlServer.ControlCommand;
import org.syncany.operations.watch.WatchOperation;
import org.syncany.util.PidFileUtil;
import com.google.common.eventbus.Subscribe;
/**
* This operation is the central part of the daemon. It can manage many different
* {@link WatchOperation}s and exposes a web socket server to control and query the
* daemon. It furthermore offers a file-based control server to stop and reload the
* daemon.
*
* <p>When started via {@link #execute()}, the operation starts the following core
* components:
*
* <ul>
* <li>The {@link WatchServer} starts a {@link WatchOperation} for every
* folder registered in the <tt>daemon.xml</tt> file. It can be reloaded via
* the <tt>syd reload</tt> command.</li>
* <li>The {@link WebServer} starts a websocket and allows clients
* (e.g. GUI, Web) to control the daemon (if authenticated).
* TODO [medium] This is not yet implemented!</li>
* <li>The {@link ControlServer} creates and watches the daemon control file
* which allows the <tt>syd</tt> shell/batch script to write reload/shutdown
* commands.</li>
* </ul>
*
* @author Vincent Wiencek <vwiencek@gmail.com>
* @author Philipp C. Heckel <philipp.heckel@gmail.com>
* @author Pim Otte
*/
public class DaemonOperation extends Operation {
private static final Logger logger = Logger.getLogger(DaemonOperation.class.getSimpleName());
private static final String PID_FILE = "daemon.pid";
private static final String DAEMON_FILE = "daemon.xml";
private static final String DAEMON_EXAMPLE_FILE = "daemon-example.xml";
private static final String DEFAULT_FOLDER = "Syncany";
private static final String USER_CLI = "CLI";
private static final String USER_ADMIN = "admin";
private File pidFile;
private WebServer webServer;
private WatchServer watchServer;
private ControlServer controlServer;
private LocalEventBus eventBus;
private DaemonConfigTO daemonConfig;
private PortTO portTO;
public DaemonOperation(Config config) {
super(config);
this.pidFile = new File(UserConfig.getUserConfigDir(), PID_FILE);
}
@Override
public OperationResult execute() throws Exception {
logger.log(Level.INFO, "Starting daemon operation ...");
startOperation();
return null;
}
private void startOperation() throws Exception {
if (PidFileUtil.isProcessRunning(pidFile)) {
throw new ServiceAlreadyStartedException("Syncany daemon already running.");
}
PidFileUtil.createPidFile(pidFile);
initEventBus();
loadOrCreateConfig();
startWebServer();
startWatchServer();
enterControlLoop(); // This blocks until SHUTDOWN is received!
}
@Subscribe
public void onControlCommand(ControlCommand controlCommand) {
switch (controlCommand) {
case SHUTDOWN:
logger.log(Level.INFO, "SHUTDOWN requested.");
stopOperation();
break;
case RELOAD:
logger.log(Level.INFO, "RELOAD requested.");
reloadOperation();
break;
}
}
// General initialization functions. These create the EventBus and control loop.
private void initEventBus() {
eventBus = LocalEventBus.getInstance();
eventBus.register(this);
}
private void enterControlLoop() throws IOException, ServiceAlreadyStartedException {
logger.log(Level.INFO, "Starting daemon control server ...");
controlServer = new ControlServer();
controlServer.enterLoop(); // This blocks!
}
// General stopping and reloading functions
private void stopOperation() {
stopWebServer();
stopWatchServer();
}
private void reloadOperation() {
loadOrCreateConfig();
watchServer.reload(daemonConfig);
}
// Config related functions. Used on starting and reloading.
private void loadOrCreateConfig() {
try {
File daemonConfigFile = new File(UserConfig.getUserConfigDir(), DAEMON_FILE);
File daemonConfigFileExample = new File(UserConfig.getUserConfigDir(), DAEMON_EXAMPLE_FILE);
if (daemonConfigFile.exists()) {
daemonConfig = DaemonConfigTO.load(daemonConfigFile);
}
else {
// Write example config to daemon-example.xml, and default config to daemon.xml
createAndWriteExampleConfig(daemonConfigFileExample);
daemonConfig = createAndWriteDefaultConfig(daemonConfigFile);
}
// Add user and password for access from the CLI
if (daemonConfig.getPortTO() == null && portTO == null) {
// Access info has not been created yet, generate new user-password pair
String accessToken = CipherUtil.createRandomAlphabeticString(20);
UserTO cliUser = new UserTO();
cliUser.setUsername(USER_CLI);
cliUser.setPassword(accessToken);
portTO = new PortTO();
portTO.setPort(daemonConfig.getWebServer().getBindPort());
portTO.setUser(cliUser);
daemonConfig.setPortTO(portTO);
}
else if (daemonConfig.getPortTO() == null) {
// Access info is not included in the daemon config, but exists. Happens when reloading.
// We reload the information about the port, but keep the access token the same.
portTO.setPort(daemonConfig.getWebServer().getBindPort());
daemonConfig.setPortTO(portTO);
}
}
catch (Exception e) {
logger.log(Level.WARNING, "Cannot (re-)load config. Exception thrown.", e);
}
}
private DaemonConfigTO createAndWriteDefaultConfig(File daemonConfigFile) {
return createAndWriteConfig(daemonConfigFile, new ArrayList<FolderTO>());
}
private DaemonConfigTO createAndWriteExampleConfig(File configFileExample) {
File defaultFolder = new File(System.getProperty("user.home"), DEFAULT_FOLDER);
FolderTO defaultFolderTO = new FolderTO();
defaultFolderTO.setPath(defaultFolder.getAbsolutePath());
ArrayList<FolderTO> folders = new ArrayList<FolderTO>();
folders.add(defaultFolderTO);
return createAndWriteConfig(configFileExample, folders);
}
private DaemonConfigTO createAndWriteConfig(File configFile, ArrayList<FolderTO> folders) {
UserTO defaultUserTO = new UserTO();
defaultUserTO.setUsername(USER_ADMIN);
defaultUserTO.setPassword(CipherUtil.createRandomAlphabeticString(12));
ArrayList<UserTO> users = new ArrayList<UserTO>();
users.add(defaultUserTO);
DaemonConfigTO defaultDaemonConfigTO = new DaemonConfigTO();
defaultDaemonConfigTO.setFolders(folders);
defaultDaemonConfigTO.setUsers(users);
try {
DaemonConfigTO.save(defaultDaemonConfigTO, configFile);
}
catch (Exception e) {
// Don't care!
}
return defaultDaemonConfigTO;
}
// Web server starting and stopping functions
private void startWebServer() throws Exception {
if (daemonConfig.getWebServer().isEnabled()) {
logger.log(Level.INFO, "Starting web server ...");
webServer = new WebServer(daemonConfig);
webServer.start();
}
else {
logger.log(Level.INFO, "Not starting web server (disabled in confi)");
}
}
private void stopWebServer() {
if (webServer != null) {
logger.log(Level.INFO, "Stopping web server ...");
webServer.stop();
}
else {
logger.log(Level.INFO, "Not stopping web server (not running)");
}
}
// Watch server starting and stopping functions
private void startWatchServer() throws ConfigException {
logger.log(Level.INFO, "Starting watch server ...");
watchServer = new WatchServer();
watchServer.start(daemonConfig);
}
private void stopWatchServer() {
logger.log(Level.INFO, "Stopping watch server ...");
watchServer.stop();
}
}