backupMainService.ts 8.2 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';
16

D
Daniel Imms 已提交
17
export class BackupMainService implements IBackupMainService {
18 19 20 21

	public _serviceBrand: any;

	protected backupHome: string;
D
Daniel Imms 已提交
22
	protected workspacesJsonPath: string;
23

24
	private backups: IBackupWorkspacesFormat;
25

26
	constructor(
27 28
		@IEnvironmentService environmentService: IEnvironmentService,
		@IConfigurationService private configurationService: IConfigurationService
29 30
	) {
		this.backupHome = environmentService.backupHome;
D
Daniel Imms 已提交
31
		this.workspacesJsonPath = environmentService.backupWorkspacesPath;
D
Daniel Imms 已提交
32

33
		this.loadSync();
34 35
	}

36
	public getWorkspaceBackupPaths(): string[] {
37
		const config = this.configurationService.getConfiguration<IFilesConfiguration>();
D
Daniel Imms 已提交
38
		if (config && config.files && config.files.hotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
39
			// Only non-folder windows are restored on main process launch when
D
Daniel Imms 已提交
40
			// hot exit is configured as onExitAndWindowClose.
41 42
			return [];
		}
43
		return this.backups.folderWorkspaces.slice(0); // return a copy
44 45
	}

46 47
	public getEmptyWorkspaceBackupPaths(): string[] {
		return this.backups.emptyWorkspaces.slice(0); // return a copy
48 49
	}

50
	public registerWindowForBackupsSync(windowId: number, isEmptyWorkspace: boolean, backupFolder?: string, workspacePath?: string): string {
51 52

		// Generate a new folder if this is a new empty workspace
D
Daniel Imms 已提交
53
		if (isEmptyWorkspace && !backupFolder) {
54
			backupFolder = this.getRandomEmptyWorkspaceId();
55 56
		}

D
Daniel Imms 已提交
57
		this.pushBackupPathsSync(isEmptyWorkspace ? backupFolder : workspacePath, isEmptyWorkspace);
58 59

		return path.join(this.backupHome, isEmptyWorkspace ? backupFolder : this.getWorkspaceHash(workspacePath));
60
	}
61

B
Benjamin Pasero 已提交
62
	private pushBackupPathsSync(workspaceIdentifier: string, isEmptyWorkspace: boolean): string {
63
		const array = isEmptyWorkspace ? this.backups.emptyWorkspaces : this.backups.folderWorkspaces;
64
		if (this.indexOf(workspaceIdentifier, isEmptyWorkspace) === -1) {
65 66
			array.push(workspaceIdentifier);
			this.saveSync();
67
		}
68 69

		return workspaceIdentifier;
70 71
	}

72 73 74
	protected removeBackupPathSync(workspaceIdentifier: string, isEmptyWorkspace: boolean): void {
		const array = isEmptyWorkspace ? this.backups.emptyWorkspaces : this.backups.folderWorkspaces;
		if (!array) {
75 76
			return;
		}
77
		const index = this.indexOf(workspaceIdentifier, isEmptyWorkspace);
78 79 80
		if (index === -1) {
			return;
		}
81
		array.splice(index, 1);
82 83 84
		this.saveSync();
	}

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
	private indexOf(workspaceIdentifier: string, isEmptyWorkspace: boolean): number {
		const array = isEmptyWorkspace ? this.backups.emptyWorkspaces : this.backups.folderWorkspaces;
		if (!array) {
			return -1;
		}

		if (isEmptyWorkspace) {
			return array.indexOf(workspaceIdentifier);
		}

		// for backup workspaces, sanitize the workspace identifier to accomodate for case insensitive file systems
		const sanitizedWorkspaceIdentifier = this.sanitizePath(workspaceIdentifier);
		return arrays.firstIndex(array, id => this.sanitizePath(id) === sanitizedWorkspaceIdentifier);
	}

100
	protected loadSync(): void {
101
		let backups: IBackupWorkspacesFormat;
D
Daniel Imms 已提交
102
		try {
103
			backups = JSON.parse(fs.readFileSync(this.workspacesJsonPath, 'utf8').toString()); // invalid JSON or permission issue can happen here
D
Daniel Imms 已提交
104
		} catch (error) {
105
			backups = Object.create(null);
D
Daniel Imms 已提交
106 107 108
		}

		// Ensure folderWorkspaces is a string[]
109 110
		if (backups.folderWorkspaces) {
			const fws = backups.folderWorkspaces;
D
Daniel Imms 已提交
111
			if (!Array.isArray(fws) || fws.some(f => typeof f !== 'string')) {
112
				backups.folderWorkspaces = [];
D
Daniel Imms 已提交
113
			}
114 115
		} else {
			backups.folderWorkspaces = [];
116 117
		}

118 119 120 121 122 123 124 125
		// 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 = [];
126 127
		}

128
		this.backups = this.dedupeFolderWorkspaces(backups);
129 130 131 132 133

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

134
	protected dedupeFolderWorkspaces(backups: IBackupWorkspacesFormat): IBackupWorkspacesFormat {
135 136 137
		// De-duplicate folder workspaces, don't worry about cleaning them up any duplicates as
		// they will be removed when there are no backups.
		backups.folderWorkspaces = arrays.distinct(backups.folderWorkspaces, ws => this.sanitizePath(ws));
138 139

		return backups;
D
Daniel Imms 已提交
140 141 142 143 144
	}

	private validateBackupWorkspaces(backups: IBackupWorkspacesFormat): void {
		const staleBackupWorkspaces: { workspaceIdentifier: string; backupPath: string; isEmptyWorkspace: boolean }[] = [];

145
		// Validate Folder Workspaces
146
		backups.folderWorkspaces.forEach(workspacePath => {
147
			const backupPath = path.join(this.backupHome, this.getWorkspaceHash(workspacePath));
148 149 150 151 152 153
			const hasBackups = this.hasBackupsSync(backupPath);
			const missingWorkspace = hasBackups && !fs.existsSync(workspacePath);

			// If the folder has no backups, make sure to delete it
			// If the folder has backups, but the target workspace is missing, convert backups to empty ones
			if (!hasBackups || missingWorkspace) {
154
				staleBackupWorkspaces.push({ workspaceIdentifier: workspacePath, backupPath, isEmptyWorkspace: false });
155 156

				if (missingWorkspace) {
157
					const identifier = this.pushBackupPathsSync(this.getRandomEmptyWorkspaceId(), true /* is empty workspace */);
158 159 160 161 162 163 164 165 166
					const newEmptyWorkspaceBackupPath = path.join(path.dirname(backupPath), identifier);
					try {
						fs.renameSync(backupPath, newEmptyWorkspaceBackupPath);
					} catch (ex) {
						console.error(`Backup: Could not rename backup folder for missing workspace: ${ex.toString()}`);

						this.removeBackupPathSync(identifier, true);
					}
				}
167 168
			}
		});
169

170
		// Validate Empty Workspaces
171 172
		backups.emptyWorkspaces.forEach(backupFolder => {
			const backupPath = path.join(this.backupHome, backupFolder);
173
			if (!this.hasBackupsSync(backupPath)) {
D
Daniel Imms 已提交
174 175 176 177
				staleBackupWorkspaces.push({ workspaceIdentifier: backupFolder, backupPath, isEmptyWorkspace: true });
			}
		});

178
		// Clean up stale backups
D
Daniel Imms 已提交
179
		staleBackupWorkspaces.forEach(staleBackupWorkspace => {
A
Alex Dima 已提交
180
			const { backupPath, workspaceIdentifier, isEmptyWorkspace } = staleBackupWorkspace;
181 182 183 184 185 186 187

			try {
				extfs.delSync(backupPath);
			} catch (ex) {
				console.error(`Backup: Could not delete stale backup: ${ex.toString()}`);
			}

188
			this.removeBackupPathSync(workspaceIdentifier, isEmptyWorkspace);
189 190 191
		});
	}

B
Benjamin Pasero 已提交
192
	private hasBackupsSync(backupPath: string): boolean {
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
		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
208 209 210 211 212 213 214 215 216
		}
	}

	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);
			}
217
			fs.writeFileSync(this.workspacesJsonPath, JSON.stringify(this.backups));
218
		} catch (ex) {
219
			console.error(`Backup: Could not save workspaces.json: ${ex.toString()}`);
220 221
		}
	}
222

B
Benjamin Pasero 已提交
223 224 225 226
	private getRandomEmptyWorkspaceId(): string {
		return (Date.now() + Math.round(Math.random() * 1000)).toString();
	}

B
Benjamin Pasero 已提交
227
	private sanitizePath(p: string): string {
D
Daniel Imms 已提交
228 229 230
		return platform.isLinux ? p : p.toLowerCase();
	}

D
Daniel Imms 已提交
231
	protected getWorkspaceHash(workspacePath: string): string {
232
		return crypto.createHash('md5').update(this.sanitizePath(workspacePath)).digest('hex');
233
	}
234
}