backupMainService.ts 7.5 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';
12
import Uri from 'vs/base/common/uri';
D
Daniel Imms 已提交
13
import { IBackupWorkspacesFormat, IBackupMainService } from 'vs/platform/backup/common/backup';
14
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
15
import { TPromise } from 'vs/base/common/winjs.base';
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;
B
Benjamin Pasero 已提交
25
	private mapWindowToBackupFolder: { [windowId: number]: string; };
26

27
	constructor(
B
Benjamin Pasero 已提交
28
		@IEnvironmentService environmentService: IEnvironmentService
29 30
	) {
		this.backupHome = environmentService.backupHome;
D
Daniel Imms 已提交
31
		this.workspacesJsonPath = environmentService.backupWorkspacesPath;
32
		this.mapWindowToBackupFolder = Object.create(null);
D
Daniel Imms 已提交
33

34
		this.loadSync();
35 36
	}

37 38 39 40 41 42 43 44
	public get workspaceBackupPaths(): string[] {
		return this.backups.folderWorkspaces;
	}

	public get emptyWorkspaceBackupPaths(): string[] {
		return this.backups.emptyWorkspaces;
	}

45 46 47 48 49 50 51 52
	public getBackupPath(windowId: number): TPromise<string> {
		if (!this.mapWindowToBackupFolder[windowId]) {
			throw new Error(`Unknown backup workspace for window ${windowId}`);
		}

		return TPromise.as(path.join(this.backupHome, this.mapWindowToBackupFolder[windowId]));
	}

B
Benjamin Pasero 已提交
53
	public registerWindowForBackupsSync(windowId: number, isEmptyWorkspace: boolean, backupFolder?: string, workspacePath?: string): void {
54
		// Generate a new folder if this is a new empty workspace
D
Daniel Imms 已提交
55
		if (isEmptyWorkspace && !backupFolder) {
56
			backupFolder = this.getRandomEmptyWorkspaceId();
57 58
		}

59
		this.mapWindowToBackupFolder[windowId] = isEmptyWorkspace ? backupFolder : this.getWorkspaceHash(workspacePath);
D
Daniel Imms 已提交
60
		this.pushBackupPathsSync(isEmptyWorkspace ? backupFolder : workspacePath, isEmptyWorkspace);
61
	}
62

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

		return workspaceIdentifier;
74 75
	}

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

89
	protected loadSync(): void {
90
		let backups: IBackupWorkspacesFormat;
D
Daniel Imms 已提交
91
		try {
92
			backups = JSON.parse(fs.readFileSync(this.workspacesJsonPath, 'utf8').toString()); // invalid JSON or permission issue can happen here
D
Daniel Imms 已提交
93
		} catch (error) {
94
			backups = Object.create(null);
D
Daniel Imms 已提交
95 96 97
		}

		// Ensure folderWorkspaces is a string[]
98 99
		if (backups.folderWorkspaces) {
			const fws = backups.folderWorkspaces;
D
Daniel Imms 已提交
100
			if (!Array.isArray(fws) || fws.some(f => typeof f !== 'string')) {
101
				backups.folderWorkspaces = [];
D
Daniel Imms 已提交
102
			}
103 104
		} else {
			backups.folderWorkspaces = [];
105 106
		}

107 108 109 110 111 112 113 114
		// 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 = [];
115 116 117 118 119 120 121 122
		}

		this.backups = backups;

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

D
Daniel Imms 已提交
123
	protected sanitizeFolderWorkspaces(backups: IBackupWorkspacesFormat): void {
124 125 126
		// Merge duplicates for folder workspaces, don't worry about cleaning them up as they will
		// be removed when there are no backups.
		backups.folderWorkspaces = arrays.distinct(backups.folderWorkspaces.map(w => this.sanitizePath(w)));
D
Daniel Imms 已提交
127 128 129 130 131 132
	}

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

		this.sanitizeFolderWorkspaces(backups);
133

134
		backups.folderWorkspaces.forEach(workspacePath => {
135
			const backupPath = path.join(this.backupHome, this.getWorkspaceHash(workspacePath));
136 137 138 139 140 141
			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) {
D
Daniel Imms 已提交
142
				const backupWorkspace = this.sanitizePath(workspacePath);
143
				staleBackupWorkspaces.push({ workspaceIdentifier: Uri.file(backupWorkspace).fsPath, backupPath, isEmptyWorkspace: false });
144 145

				if (missingWorkspace) {
146
					const identifier = this.pushBackupPathsSync(this.getRandomEmptyWorkspaceId(), true /* is empty workspace */);
147 148 149 150 151 152 153 154 155
					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);
					}
				}
156 157
			}
		});
158 159 160

		backups.emptyWorkspaces.forEach(backupFolder => {
			const backupPath = path.join(this.backupHome, backupFolder);
161
			if (!this.hasBackupsSync(backupPath)) {
D
Daniel Imms 已提交
162 163 164 165 166 167
				staleBackupWorkspaces.push({ workspaceIdentifier: backupFolder, backupPath, isEmptyWorkspace: true });
			}
		});

		staleBackupWorkspaces.forEach(staleBackupWorkspace => {
			const {backupPath, workspaceIdentifier, isEmptyWorkspace} = staleBackupWorkspace;
168 169 170 171 172 173 174

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

175
			this.removeBackupPathSync(workspaceIdentifier, isEmptyWorkspace);
176 177 178
		});
	}

B
Benjamin Pasero 已提交
179
	private hasBackupsSync(backupPath: string): boolean {
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
		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
195 196 197 198 199 200 201 202 203
		}
	}

	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);
			}
204
			fs.writeFileSync(this.workspacesJsonPath, JSON.stringify(this.backups));
205
		} catch (ex) {
206
			console.error(`Backup: Could not save workspaces.json: ${ex.toString()}`);
207 208
		}
	}
209

B
Benjamin Pasero 已提交
210 211 212 213
	private getRandomEmptyWorkspaceId(): string {
		return (Date.now() + Math.round(Math.random() * 1000)).toString();
	}

B
Benjamin Pasero 已提交
214
	private sanitizePath(p: string): string {
D
Daniel Imms 已提交
215 216 217
		return platform.isLinux ? p : p.toLowerCase();
	}

D
Daniel Imms 已提交
218
	protected getWorkspaceHash(workspacePath: string): string {
219
		return crypto.createHash('md5').update(this.sanitizePath(workspacePath)).digest('hex');
220
	}
221
}