Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ask pull secret during start #21

Merged
merged 5 commits into from
Mar 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 41 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "crc",
"displayName": "CRC",
"description": "Allows the ability to start and stop CRC and use Podman Desktop to interact with it",
"name": "openshift-local",
"displayName": "OpenShift Local",
"description": "Allows the ability to start and stop OpenShift Local and use Podman Desktop to interact with it",
"version": "0.0.1",
"icon": "icon.png",
"publisher": "benoitf",
Expand All @@ -17,7 +17,44 @@
"command": "crc.info",
"title": "crc: Specific info about crc"
}
]
],
"configuration": {
"title": "OpenShift Local",
"properties": {
"crc.factory.memory": {
"type": "number",
"format": "memory",
"minimum": 8192,
"default": 9216,
"description": "Memory size in MiB (must be greater than or equal to '2048')"
},
"crc.cpus": {
"type": "number",
"format": "cpu",
"minimum": 4,
"default": 4,
"description": "Number of CPU cores (must be greater than or equal to '4')"
},
"crc.preset": {
"type": "string",
"enum": ["openshift", "microshift"],
"default": "openshift",
"description": "OpenShift Local Virtual machine preset"
},
"crc.disksize": {
"type": "number",
"format": "memory",
"default": 31,
"minimum": 20,
"description": "Disk size (GiB)"
},
"crc.pullsecretfile": {
"type": "string",
"format": "file",
"description": "Path of image pull secret (download from https://console.redhat.com/openshift/create/local)(Optional)"
}
}
}
},
"scripts": {
"build": "rollup --bundleConfigAsCjs --config rollup.config.js --compact --environment BUILD:production && node ./scripts/build.js",
Expand Down
2 changes: 1 addition & 1 deletion rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export default {
'node:worker_threads',
],
plugins: [
typescript(),
typescript({ noEmitOnError: true }),
commonjs({ extensions: ['.js', '.ts'] }), // the ".ts" extension is required],
json(),
nodeResolve({preferBuiltins: true}),
Expand Down
7 changes: 5 additions & 2 deletions scripts/run.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const pack = await fs.promises.readFile(path.resolve(__dirname, '../package.json'));
const packageJson = JSON.parse(pack);

const desktopPath = path.join(__dirname, '..', '..', 'podman-desktop');

async function exec(command, args, options) {
Expand Down Expand Up @@ -78,11 +81,11 @@ async function buildPD() {
async function buildCrc() {
await exec('yarn',['build'], {cwd: path.join(__dirname, '..')});

const pluginsPath = path.resolve(os.homedir(), '.local/share/containers/podman-desktop/plugins/crc.cdix/');
const pluginsPath = path.resolve(os.homedir(), `.local/share/containers/podman-desktop/plugins/${packageJson.name}.cdix/`);
fs.rmSync(pluginsPath, { recursive: true, force: true });

fs.mkdirSync(pluginsPath, {recursive: true});
fs.cpSync(path.resolve(__dirname,'..', 'builtin' ,'crc.cdix'), pluginsPath, {recursive: true});
fs.cpSync(path.resolve(__dirname,'..', 'builtin' ,`${packageJson.name}.cdix/`), pluginsPath, {recursive: true});
}

async function build() {
Expand Down
9 changes: 0 additions & 9 deletions src/crc-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,12 +168,3 @@ export function daemonStop() {
daemonProcess.kill();
}
}

export async function needSetup(): Promise<boolean> {
try {
await execPromise(getCrcCli(), ['setup', '--check-only']);
return false;
} catch (e) {
return true;
}
}
13 changes: 13 additions & 0 deletions src/crc-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,19 @@ interface PresetQuickPickItem extends extensionApi.QuickPickItem {
data: Preset;
}

export let isNeedSetup = false;

export async function needSetup(): Promise<boolean> {
try {
await execPromise(getCrcCli(), ['setup', '--check-only']);
isNeedSetup = false;
return false;
} catch (e) {
isNeedSetup = true;
return true;
}
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export async function setUpCrc(logger: extensionApi.Logger, askForPreset = false): Promise<boolean> {
if (askForPreset) {
Expand Down
103 changes: 103 additions & 0 deletions src/crc-start.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/**********************************************************************
* Copyright (C) 2023 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/

import * as extensionApi from '@podman-desktop/api';
import { isNeedSetup, needSetup, setUpCrc } from './crc-setup';
import { crcStatus } from './crc-status';
import { commander } from './daemon-commander';
import { crcLogProvider } from './log-provider';

interface ImagePullSecret {
auths: { auth: string; credsStore: string }[];
}

const missingPullSecret = 'Failed to ask for pull secret';

export async function startCrc(logger: extensionApi.Logger): Promise<void> {
try {
// call crc setup to prepare bundle, before start
if (isNeedSetup) {
try {
crcStatus.setSetupRunning(true);
await setUpCrc(logger);
await needSetup();
} catch (error) {
logger.error(error);
return;
} finally {
crcStatus.setSetupRunning(false);
}
}
crcLogProvider.startSendingLogs(logger);
const result = await commander.start();
console.error('StartResult:' + JSON.stringify(result));
} catch (err) {
if (typeof err.message === 'string') {
// check that crc missing pull secret
if (err.message.startsWith(missingPullSecret)) {
// ask user to provide pull secret
if (await askAndStorePullSecret(logger)) {
// if pull secret provided try to start again
return startCrc(logger);
}
return;
} else if (err.name === 'RequestError' && err.code === 'ECONNRESET') {
// look like crc start normally, but we receive empty response from socket, so 'got' generate an error
return;
}
}

console.error(err);
}
}

async function askAndStorePullSecret(logger: extensionApi.Logger): Promise<boolean> {
const pullSecret = await extensionApi.window.showInputBox({
prompt: 'Provide a pull secret',
// prompt: 'To pull container images from the registry, a pull secret is necessary.',
ignoreFocusOut: true,
});

if (!pullSecret) {
return false;
}
try {
const s: ImagePullSecret = JSON.parse(pullSecret);
if (s.auths && s.auths.length > 0) {
for (const a of s.auths) {
if (!a.auth && !a.credsStore) {
throw `${JSON.stringify(s)} JSON-object requires either 'auth' or 'credsStore' field`;
}
}
} else {
throw 'missing "auths" JSON-object field';
}
} catch (err) {
// not valid json
extensionApi.window.showErrorMessage(`Start failed, pull secret is not valid. Please start again:\n '${err}'`);
return false;
}
try {
await commander.pullSecretStore(pullSecret);
return true;
} catch (error) {
console.error(error);
logger.error(error);
}
return false;
}
130 changes: 130 additions & 0 deletions src/crc-status.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/**********************************************************************
* Copyright (C) 2023 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/

import type * as extensionApi from '@podman-desktop/api';
import type { Status, CrcStatus as CrcStatusApi } from './daemon-commander';
import { commander } from './daemon-commander';

const defaultStatus: Status = { CrcStatus: 'Unknown', Preset: 'Unknown' };
const errorStatus: Status = { CrcStatus: 'Error', Preset: 'Unknown' };

export class CrcStatus {
private updateTimer: NodeJS.Timer;
private _status: Status;
private isSetupGoing: boolean;

constructor() {
this._status = defaultStatus;
}

startStatusUpdate(): void {
if (this.updateTimer) {
return; // we already set timer
}
this.updateTimer = setInterval(async () => {
try {
// we don't need to update status while setup is going
if (this.isSetupGoing) {
this._status = createStatus('Starting', this._status.Preset);
return;
}
this._status = await commander.status();
} catch (e) {
console.error('CRC Status tick: ' + e);
this._status = defaultStatus;
}
}, 1000);
}

stopStatusUpdate(): void {
if (this.updateTimer) {
clearInterval(this.updateTimer);
}
}

get status(): Status {
return this._status;
}

setErrorStatus(): void {
this._status = errorStatus;
}

async initialize(): Promise<void> {
try {
// initial status
this._status = await commander.status();
} catch (err) {
console.error('error in CRC extension', err);
this._status = defaultStatus;
}
}

setSetupRunning(setup: boolean): void {
if (setup) {
this.isSetupGoing = true;
this._status = createStatus('Starting', this._status.Preset);
} else {
this.isSetupGoing = false;
}
}

getConnectionStatus(): extensionApi.ProviderConnectionStatus {
switch (this._status.CrcStatus) {
case 'Running':
return 'started';
case 'Starting':
return 'starting';
case 'Stopping':
return 'stopping';
case 'Stopped':
case 'No Cluster':
return 'stopped';
default:
return 'unknown';
}
}

getProviderStatus(): extensionApi.ProviderStatus {
switch (this._status.CrcStatus) {
case 'Running':
return 'started';
case 'Starting':
return 'starting';
case 'Stopping':
return 'stopping';
case 'Stopped':
return 'stopped';
case 'No Cluster':
return 'stopped';
case 'Error':
return 'error';
default:
return 'not-installed';
}
}
}

function createStatus(crcStatus: CrcStatusApi, preset: string): Status {
return {
CrcStatus: crcStatus,
Preset: preset,
};
}

export const crcStatus = new CrcStatus();
Loading