backupMainService.ts 9.9 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import * as arrays from 'vs/base/common/arrays';
7 8
import * as fs from 'fs';
import * as path from 'path';
9
import * as crypto from 'crypto';
10
import * as platform from 'vs/base/common/platform';
11
import * as extfs from 'vs/base/node/extfs';
D
Daniel Imms 已提交
12
import { IBackupWorkspacesFormat, IBackupMainService } from 'vs/platform/backup/common/backup';
13
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
14 15
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IFilesConfiguration, HotExitConfiguration } from 'vs/platform/files/common/files';
B
Benjamin Pasero 已提交
16
import { ILogService } from "vs/platform/log/common/log";
17
import { IWorkspaceIdentifier } from "vs/platform/workspaces/common/workspaces";
18

D
Daniel Imms 已提交
19
export class BackupMainService implements IBackupMainService {
20 21 22 23

	public _serviceBrand: any;

	protected backupHome: string;
D
Daniel Imms 已提交
24
	protected workspacesJsonPath: string;
25

26
	protected backups: IBackupWorkspacesFormat;
27

28
	constructor(
29
		@IEnvironmentService environmentService: IEnvironmentService,
B
Benjamin Pasero 已提交
30 31
		@IConfigurationService private configurationService: IConfigurationService,
		@ILogService private logService: ILogService
32 33
	) {
		this.backupHome = environmentService.backupHome;
D
Daniel Imms 已提交
34
		this.workspacesJsonPath = environmentService.backupWorkspacesPath;
D
Daniel Imms 已提交
35

36
		this.loadSync();
37 38
	}

39
	public getWorkspaceBackups(): IWorkspaceIdentifier[] {
40 41 42 43 44 45 46 47 48 49
		if (this.isHotExitOnExitAndWindowClose()) {
			// Only non-folder windows are restored on main process launch when
			// hot exit is configured as onExitAndWindowClose.
			return [];
		}
		return this.backups.rootWorkspaces.slice(0); // return a copy
	}

	public getFolderBackupPaths(): string[] {
		if (this.isHotExitOnExitAndWindowClose()) {
50
			// Only non-folder windows are restored on main process launch when
D
Daniel Imms 已提交
51
			// hot exit is configured as onExitAndWindowClose.
52 53
			return [];
		}
54
		return this.backups.folderWorkspaces.slice(0); // return a copy
55 56
	}

57 58 59 60 61 62
	private isHotExitOnExitAndWindowClose(): boolean {
		const config = this.configurationService.getConfiguration<IFilesConfiguration>();

		return config && config.files && config.files.hotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE;
	}

63
	public getEmptyWindowBackupPaths(): string[] {
64
		return this.backups.emptyWorkspaces.slice(0); // return a copy
65 66
	}

67
	public registerWorkspaceBackupSync(workspace: IWorkspaceIdentifier): string {
68
		this.pushBackupPathsSync(workspace, this.backups.rootWorkspaces);
69

70
		return path.join(this.backupHome, workspace.id);
71 72
	}

B
Benjamin Pasero 已提交
73
	public registerFolderBackupSync(folderPath: string): string {
74
		this.pushBackupPathsSync(folderPath, this.backups.folderWorkspaces);
B
Benjamin Pasero 已提交
75

76
		return path.join(this.backupHome, this.getFolderHash(folderPath));
B
Benjamin Pasero 已提交
77 78 79
	}

	public registerEmptyWindowBackupSync(backupFolder?: string): string {
80 81

		// Generate a new folder if this is a new empty workspace
B
Benjamin Pasero 已提交
82
		if (!backupFolder) {
83
			backupFolder = this.getRandomEmptyWindowId();
84 85
		}

86
		this.pushBackupPathsSync(backupFolder, this.backups.emptyWorkspaces);
87

B
Benjamin Pasero 已提交
88
		return path.join(this.backupHome, backupFolder);
89
	}
90

91
	private pushBackupPathsSync(workspaceIdentifier: string | IWorkspaceIdentifier, target: (string | IWorkspaceIdentifier)[]): void {
92 93
		if (this.indexOf(workspaceIdentifier, target) === -1) {
			target.push(workspaceIdentifier);
94
			this.saveSync();
95 96 97
		}
	}

98
	protected removeBackupPathSync(workspaceIdentifier: string | IWorkspaceIdentifier, target: (string | IWorkspaceIdentifier)[]): void {
99
		if (!target) {
100 101
			return;
		}
102
		const index = this.indexOf(workspaceIdentifier, target);
103 104 105
		if (index === -1) {
			return;
		}
106
		target.splice(index, 1);
107 108 109
		this.saveSync();
	}

110
	private indexOf(workspaceIdentifier: string | IWorkspaceIdentifier, target: (string | IWorkspaceIdentifier)[]): number {
111
		if (!target) {
112 113 114
			return -1;
		}

115 116 117 118 119
		const sanitizedWorkspaceIdentifier = this.sanitizeId(workspaceIdentifier);

		return arrays.firstIndex(target, id => this.sanitizeId(id) === sanitizedWorkspaceIdentifier);
	}

120
	private sanitizeId(workspaceIdentifier: string | IWorkspaceIdentifier): string {
121 122 123
		if (typeof workspaceIdentifier === 'string') {
			return this.sanitizePath(workspaceIdentifier);
		}
124

125
		return workspaceIdentifier.id;
126 127
	}

128
	protected loadSync(): void {
129
		let backups: IBackupWorkspacesFormat;
D
Daniel Imms 已提交
130
		try {
131
			backups = JSON.parse(fs.readFileSync(this.workspacesJsonPath, 'utf8').toString()); // invalid JSON or permission issue can happen here
D
Daniel Imms 已提交
132
		} catch (error) {
133
			backups = Object.create(null);
D
Daniel Imms 已提交
134 135
		}

136
		// Ensure rootWorkspaces is a object[]
137 138
		if (backups.rootWorkspaces) {
			const rws = backups.rootWorkspaces;
139
			if (!Array.isArray(rws) || rws.some(r => typeof r !== 'object')) {
140 141 142 143 144 145
				backups.rootWorkspaces = [];
			}
		} else {
			backups.rootWorkspaces = [];
		}

D
Daniel Imms 已提交
146
		// Ensure folderWorkspaces is a string[]
147 148
		if (backups.folderWorkspaces) {
			const fws = backups.folderWorkspaces;
D
Daniel Imms 已提交
149
			if (!Array.isArray(fws) || fws.some(f => typeof f !== 'string')) {
150
				backups.folderWorkspaces = [];
D
Daniel Imms 已提交
151
			}
152 153
		} else {
			backups.folderWorkspaces = [];
154 155
		}

156 157 158 159 160 161 162 163
		// Ensure emptyWorkspaces is a string[]
		if (backups.emptyWorkspaces) {
			const fws = backups.emptyWorkspaces;
			if (!Array.isArray(fws) || fws.some(f => typeof f !== 'string')) {
				backups.emptyWorkspaces = [];
			}
		} else {
			backups.emptyWorkspaces = [];
164 165
		}

166
		this.backups = this.dedupeBackups(backups);
167 168 169 170 171

		// Validate backup workspaces
		this.validateBackupWorkspaces(backups);
	}

172 173 174
	protected dedupeBackups(backups: IBackupWorkspacesFormat): IBackupWorkspacesFormat {

		// De-duplicate folder/workspace backups. don't worry about cleaning them up any duplicates as
175 176
		// they will be removed when there are no backups.
		backups.folderWorkspaces = arrays.distinct(backups.folderWorkspaces, ws => this.sanitizePath(ws));
177
		backups.rootWorkspaces = arrays.distinct(backups.rootWorkspaces, ws => this.sanitizePath(ws.id));
178 179

		return backups;
D
Daniel Imms 已提交
180 181 182
	}

	private validateBackupWorkspaces(backups: IBackupWorkspacesFormat): void {
183
		const staleBackupWorkspaces: { workspaceIdentifier: string | IWorkspaceIdentifier; backupPath: string; target: (string | IWorkspaceIdentifier)[] }[] = [];
184

185
		const workspaceAndFolders: { workspaceIdentifier: string | IWorkspaceIdentifier, target: (string | IWorkspaceIdentifier)[] }[] = [];
186 187
		workspaceAndFolders.push(...backups.rootWorkspaces.map(r => ({ workspaceIdentifier: r, target: backups.rootWorkspaces })));
		workspaceAndFolders.push(...backups.folderWorkspaces.map(f => ({ workspaceIdentifier: f, target: backups.folderWorkspaces })));
D
Daniel Imms 已提交
188

189 190
		// Validate Workspace and Folder Backups
		workspaceAndFolders.forEach(workspaceOrFolder => {
191 192 193
			const workspaceId = workspaceOrFolder.workspaceIdentifier;
			const workspacePath = typeof workspaceId === 'string' ? workspaceId : workspaceId.configPath;
			const backupPath = path.join(this.backupHome, typeof workspaceId === 'string' ? this.getFolderHash(workspaceId) : workspaceId.id);
194
			const hasBackups = this.hasBackupsSync(backupPath);
195
			const missingWorkspace = hasBackups && !fs.existsSync(workspacePath);
196

197 198
			// If the workspace/folder has no backups, make sure to delete it
			// If the workspace/folder has backups, but the target workspace is missing, convert backups to empty ones
199
			if (!hasBackups || missingWorkspace) {
200
				staleBackupWorkspaces.push({ workspaceIdentifier: workspaceId, backupPath, target: workspaceOrFolder.target });
201 202

				if (missingWorkspace) {
203 204
					const identifier = this.getRandomEmptyWindowId();
					this.pushBackupPathsSync(identifier, this.backups.emptyWorkspaces);
205
					const newEmptyWindowBackupPath = path.join(path.dirname(backupPath), identifier);
206
					try {
207
						fs.renameSync(backupPath, newEmptyWindowBackupPath);
208
					} catch (ex) {
B
Benjamin Pasero 已提交
209
						this.logService.error(`Backup: Could not rename backup folder for missing workspace: ${ex.toString()}`);
210

211
						this.removeBackupPathSync(identifier, this.backups.emptyWorkspaces);
212 213
					}
				}
214 215
			}
		});
216

217
		// Validate Empty Windows
218 219
		backups.emptyWorkspaces.forEach(backupFolder => {
			const backupPath = path.join(this.backupHome, backupFolder);
220
			if (!this.hasBackupsSync(backupPath)) {
221
				staleBackupWorkspaces.push({ workspaceIdentifier: backupFolder, backupPath, target: backups.emptyWorkspaces });
D
Daniel Imms 已提交
222 223 224
			}
		});

225
		// Clean up stale backups
D
Daniel Imms 已提交
226
		staleBackupWorkspaces.forEach(staleBackupWorkspace => {
227
			const { backupPath, workspaceIdentifier, target } = staleBackupWorkspace;
228 229 230 231

			try {
				extfs.delSync(backupPath);
			} catch (ex) {
B
Benjamin Pasero 已提交
232
				this.logService.error(`Backup: Could not delete stale backup: ${ex.toString()}`);
233 234
			}

235
			this.removeBackupPathSync(workspaceIdentifier, target);
236 237 238
		});
	}

B
Benjamin Pasero 已提交
239
	private hasBackupsSync(backupPath: string): boolean {
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
		try {
			const backupSchemas = extfs.readdirSync(backupPath);
			if (backupSchemas.length === 0) {
				return false; // empty backups
			}

			return backupSchemas.some(backupSchema => {
				try {
					return extfs.readdirSync(path.join(backupPath, backupSchema)).length > 0;
				} catch (error) {
					return false; // invalid folder
				}
			});
		} catch (error) {
			return false; // backup path does not exist
255 256 257 258 259 260 261 262 263
		}
	}

	private saveSync(): void {
		try {
			// The user data directory must exist so only the Backup directory needs to be checked.
			if (!fs.existsSync(this.backupHome)) {
				fs.mkdirSync(this.backupHome);
			}
264
			fs.writeFileSync(this.workspacesJsonPath, JSON.stringify(this.backups));
265
		} catch (ex) {
B
Benjamin Pasero 已提交
266
			this.logService.error(`Backup: Could not save workspaces.json: ${ex.toString()}`);
267 268
		}
	}
269

270
	private getRandomEmptyWindowId(): string {
B
Benjamin Pasero 已提交
271 272 273
		return (Date.now() + Math.round(Math.random() * 1000)).toString();
	}

B
Benjamin Pasero 已提交
274
	private sanitizePath(p: string): string {
D
Daniel Imms 已提交
275 276 277
		return platform.isLinux ? p : p.toLowerCase();
	}

278 279
	protected getFolderHash(folderPath: string): string {
		return crypto.createHash('md5').update(this.sanitizePath(folderPath)).digest('hex');
280
	}
281
}