Running "yarn hardhat deploy --tags mocks' to but its running other files. Do i need any specific dependencies? If so how can i check? - deployment

This is the file i am trying to deploy for testing, called "00-deploy-mocks":
const { network } = require("hardhat")
const {
developmentChains,
DECIMALS,
initialAnswer
} = require("../helper-hardhat-config")
module.exports = async ({ getNamedAccounts, deployments }) => {
const { deploy, log } = deployments
const { deployer } = getNamedAccounts()
const chainId = network.config.chainId
// If we are on a local development network, we need to deploy mocks!
if (developmentChains.includes(network.name)) {
log("Local network detected! Deploying mocks...")
await deploy("MockV3Aggregator", {
contract: "MockV3Aggregator",
from: deployer,
log: true,
args: [DECIMALS, initialAnswer]
})
log("Mocks Deployed!")
log("------------------------------------------------")
}
}
module.exports.tags = ["all", "mocks"]
This is the error im getting:
yarn run v1.22.15
warning package.json: No license field
$ /home/fbaqueriza/hh-fcc/hardhat-fund-me-fcc/node_modules/.bin/hardhat deploy --tags mocks
Nothing to compile
An unexpected error occurred:
Error: ERROR processing skip func of /home/fbaqueriza/hh-fcc/hardhat-fund-me-fcc/deploy/01-deploy-fund-me.js:
/home/fbaqueriza/hh-fcc/hardhat-fund-me-fcc/deploy/01-deploy-fund-me.js:29
const fundMe = await deploy("FundMe", {
^^^^^

Related

SonarQube does not calculate code coverage

I am using postgres sql as my DB in my springboot application .
My SonarQube is unable to calculate code coverage.can someone please guide me in this
build.gradle
plugins {
id 'org.springframework.boot' version "${springBootVersion}"
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
id 'java'
id 'eclipse'
id 'jacoco'
id 'org.sonarqube' version "3.3"
id 'com.google.cloud.tools.jib' version "${jibVersion}"
}
group = 'com.vsi.postgrestoattentive'
if (!project.hasProperty('buildName')) {
throw new GradleException("Usage for CLI:"
+ System.getProperty("line.separator")
+ "gradlew <taskName> -Dorg.gradle.java.home=<java-home-dir> -PbuildName=<major>.<minor>.<buildNumber> -PgcpProject=<gcloudProject>"
+ System.getProperty("line.separator")
+ "<org.gradle.java.home> - OPTIONAL if available in PATH"
+ System.getProperty("line.separator")
+ "<buildName> - MANDATORY, example 0.1.23")
+ System.getProperty("line.separator")
+ "<gcpProject> - OPTIONAL, project name in GCP";
}
project.ext {
buildName = project.property('buildName');
}
version = "${project.ext.buildName}"
sourceCompatibility = '1.8'
apply from: 'gradle/sonar.gradle'
apply from: 'gradle/tests.gradle'
apply from: 'gradle/image-build-gcp.gradle'
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
implementation("org.springframework.boot:spring-boot-starter-actuator:${springBootVersion}")
implementation 'org.springframework.boot:spring-boot-starter-web:2.7.0'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.integration:spring-integration-test'
testImplementation 'org.springframework.batch:spring-batch-test:4.3.0'
implementation("org.springframework.boot:spring-boot-starter-data-jpa:${springBootVersion}")
implementation 'org.postgresql:postgresql:42.2.16'
implementation 'org.springframework.batch:spring-batch-core:4.1.1.RELEASE'
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.14.1'
implementation group: 'io.micrometer', name: 'micrometer-registry-datadog', version: '1.7.0'
implementation 'com.google.cloud:libraries-bom:26.3.0'
implementation 'com.google.cloud:google-cloud-storage:2.16.0'
testImplementation('org.mockito:mockito-core:3.7.7')
//Below 4 dependencies should be commented in local
implementation 'org.springframework.cloud:spring-cloud-starter-kubernetes-client-all:2.0.4'
implementation 'io.kubernetes:client-java:12.0.0'
implementation("org.springframework.cloud:spring-cloud-gcp-starter-metrics:${gcpSpringCloudVersion}")
implementation 'org.springframework.cloud:spring-cloud-gcp-logging:1.2.8.RELEASE'
testImplementation('org.mockito:mockito-core:3.7.7')
testImplementation 'org.springframework.boot:spring-boot-test'
testImplementation 'org.springframework:spring-test'
testImplementation 'org.assertj:assertj-core:3.21.0'
testImplementation("org.springframework.boot:spring-boot-starter-test:${springBootVersion}") {
exclude group: "org.junit.vintage", module: "junit-vintage-engine"
}
}
bootJar {
archiveFileName = "${project.name}.${archiveExtension.get()}"
}
springBoot {
buildInfo()
}
test {
finalizedBy jacocoTestReport
}
jacoco {
toolVersion = "0.8.8"
}
jacocoTestReport {
dependsOn test
}
//: Code to make build check code coverage ratio
project.tasks["bootJar"].dependsOn "jacocoTestReport","jacocoTestCoverageVerification"
tests.gradle
test {
finalizedBy jacocoTestReport
useJUnitPlatform()
testLogging {
exceptionFormat = 'full'
}
afterSuite { desc, result ->
if (!desc.parent) {
println "Results: (${result.testCount} tests, ${result.successfulTestCount} successes, ${result.failedTestCount} failures, ${result.skippedTestCount} skipped)"
boolean skipTests = Boolean.parseBoolean(project.findProperty('SKIP_TESTS') ?: "false")
if (result.testCount == 0 && !skipTests) {
throw new IllegalStateException("No tests were found. Failing the build")
}
}
}
jacocoTestCoverageVerification {
dependsOn test
violationRules {
rule{
limit {
//SMS-28: Since project is in nascent stage setting code coverage ratio limit to 1%
minimum = 0.5
}
}
}
}
}
sonar.gradle
apply plugin: "org.sonarqube"
apply plugin: 'jacoco'
jacoco {
toolVersion = "0.8.5"
reportsDir = file("$buildDir/jacoco")
}
jacocoTestReport {
reports {
xml.enabled true
html.enabled true
csv.enabled false
}
}
JenkinsBuildFile
pipeline {
agent any
environment {
// TODO: Remove this
GIT_BRANCH_LOCAL = sh (
script: "echo $GIT_BRANCH | sed -e 's|origin/||g'",
returnStdout: true
).trim()
CURRENT_BUILD_DISPLAY="0.1.${BUILD_NUMBER}"
PROJECT_FOLDER="."
PROJECT_NAME="xyz"
//Adding default values for env variables that sometimes get erased from GCP Jenkins
GRADLE_JAVA_HOME="/opt/java/openjdk"
GCP_SA="abc"
GCP_PROJECT="efg"
SONAR_JAVA_HOME="/usr/lib/jvm/java-17-openjdk-amd64"
SONAR_HOST="http://sonar-sonarqube:9000/sonar"
}
stages {
stage('Clean Workspace') {
steps {
echo "Setting current build to ${CURRENT_BUILD_DISPLAY}"
script {
currentBuild.displayName = "${CURRENT_BUILD_DISPLAY}"
currentBuild.description = """Branch - ${GIT_BRANCH_LOCAL}"""
}
dir("${PROJECT_FOLDER}") {
echo "Changed directory to ${PROJECT_FOLDER}"
echo 'Cleaning up Work Dir...'
// Had to add below chmod command as Jenkins build was failing stating gradlew permission denied
sh 'chmod +x gradlew'
//gradlew clean means deletion of the build directory.
sh './gradlew clean -PbuildName=${CURRENT_BUILD_DISPLAY} -Dorg.gradle.java.home=${GRADLE_JAVA_HOME}'
//mkdir -p creates subdirectories
//touch creates new empty file
sh 'mkdir -p build/libs && touch build/libs/${PROJECT_NAME}-${CURRENT_BUILD_DISPLAY}.jar'
}
}
}
stage('Tests And Code Quality') {
steps {
dir("${PROJECT_FOLDER}") {
echo 'Running Tests and SonarQube Analysis'
withCredentials([string(credentialsId: 'sonar_key', variable: 'SONAR_KEY')]) {
sh '''
./gradlew -i sonarqube -Dorg.gradle.java.home=${SONAR_JAVA_HOME} \
-Dsonar.host.url=${SONAR_HOST} \
-PbuildName=${CURRENT_BUILD_DISPLAY} \
-Dsonar.login=$SONAR_KEY \
-DprojectVersion=${CURRENT_BUILD_DISPLAY}
'''
}
echo 'Ran SonarQube Analysis successfully'
}
}
}
stage('ECRContainerRegistry') {
steps {
withCredentials([file(credentialsId: 'vsi-ops-gcr', variable: 'SECRET_JSON')]) {
echo 'Activating gcloud SDK Service Account...'
sh 'gcloud auth activate-service-account $GCP_SA --key-file $SECRET_JSON --project=$GCP_PROJECT'
sh 'gcloud auth configure-docker'
echo 'Activated gcloud SDK Service Account'
dir("${PROJECT_FOLDER}") {
echo "Pushing image to GCR with tag ${CURRENT_BUILD_DISPLAY}..."
sh './gradlew jib -PbuildName=${CURRENT_BUILD_DISPLAY} -PgcpProject=${GCP_PROJECT} -Dorg.gradle.java.home=${GRADLE_JAVA_HOME}'
echo "Pushed image to GCR with tag ${CURRENT_BUILD_DISPLAY} successfully"
}
echo 'Revoking gcloud SDK Service Account...'
sh "gcloud auth revoke ${GCP_SA}"
echo 'Revoked gcloud SDK Service Account'
}
}
}
}
post {
/*
TODO: use cleanup block
deleteDir is explicit in failure because always block is run
before success causing archive failure. Also cleanup block is not
available in this version on Jenkins ver. 2.164.2
*/
success {
dir("${PROJECT_FOLDER}") {
echo 'Archiving build artifacts...'
archiveArtifacts artifacts: "build/libs/*.jar, config/**/*", fingerprint: true, onlyIfSuccessful: true
echo 'Archived build artifacts successfully'
echo 'Publising Jacoco Reports...'
jacoco(
execPattern: 'build/jacoco/*.exec',
classPattern: 'build/classes',
sourcePattern: 'src/main/java',
exclusionPattern: 'src/test*'
)
echo 'Published Jacoco Reports successfully'
}
echo 'Cleaning up workspace...'
deleteDir()
}
failure {
echo 'Cleaning up workspace...'
deleteDir()
}
aborted {
echo 'Cleaning up workspace...'
deleteDir()
}
}
}
Below is the error which i get in Jenkins console
> Task :sonarqube
JaCoCo report task detected, but XML report is not enabled or it was not produced. Coverage for this task will not be reported.
Caching disabled for task ':sonarqube' because:
Build cache is disabled
Task ':sonarqube' is not up-to-date because:
Task has not declared any outputs despite executing actions.
JaCoCo report task detected, but XML report is not enabled or it was not produced. Coverage for this task will not be reported.
User cache: /var/jenkins_home/.sonar/cache
Default locale: "en", source code encoding: "UTF-8"
Load global settings
Load global settings (done) | time=101ms
Server id: 4AE86E0C-AX63D7IJvl7jEHIL9nIz
User cache: /var/jenkins_home/.sonar/cache
Load/download plugins
Load plugins index
Load plugins index (done) | time=48ms
Load/download plugins (done) | time=91ms
Process project properties
Process project properties (done) | time=9ms
Execute project builders
Execute project builders (done) | time=1ms
Java "Test" source files AST scan (done) | time=779ms
No "Generated" source files to scan.
Sensor JavaSensor [java] (done) | time=8057ms
Sensor JaCoCo XML Report Importer [jacoco]
'sonar.coverage.jacoco.xmlReportPaths' is not defined. Using default locations: target/site/jacoco/jacoco.xml,target/site/jacoco-it/jacoco.xml,build/reports/jacoco/test/jacocoTestReport.xml
No report imported, no coverage information will be imported by JaCoCo XML Report Importer
Sensor JaCoCo XML Report Importer [jacoco] (done) | time=4ms
Can someone please guide me how to resolve this issue of sonar not calculating code coverage
While it could be caused by a number of things, from the logs, it seems likely that it couldn't find the report.
As the first comment says, check to verify that the report is being generated (but not found). If it is generated, then its likely SQ can't find the XML Jacoco report.
Note the error line, near the end:
'sonar.coverage.jacoco.xmlReportPaths' is not defined. Using default locations: target/site/jacoco/jacoco.xml,target/site/jacoco-it/jacoco.xml,build/reports/jacoco/test/jacocoTestReport.xml
An example of defining this location this would be putting this line in sonar-project.properties:
sonar.coverage.jacoco.xmlReportsPaths=build/reports/jacoco.xml
It can also be defined directly in a *.gradle file:
sonarqube {
properties {
property "sonar.coverage.jacoco.xmlReportsPaths", "build/reports/jacoco.xml"
}
}

Deploy docker image from Nexus registry

I have this Jenkinsfile which I want to use to build a pipeline:
pipeline {
agent any
environment {
NEXUS_VERSION = "nexus3"
NEXUS_PROTOCOL = "http"
NEXUS_URL = "you-ip-addr-here:8081"
NEXUS_REPOSITORY = "maven-nexus-repo"
NEXUS_CREDENTIAL_ID = "nexus-user-credentials"
}
stages {
stage('Download Helm Charts') {
steps {
sh "echo 'Downloading Helm Charts from Bitbucket repository...'"
// configure credentials under http://192.168.1.28:8080/user/test/credentials/ and put credentials ID
// not sure do I need to point the root folder of the Helm repository or only the single chart
checkout scmGit(
branches: [[name: 'master']],
userRemoteConfigs: [[credentialsId: 'c2672602-dfd5-4158-977c-5009065c867e',
url: 'http://192.168.1.30:7990/scm/jen/helm.git']])
}
}
stage('Test Kubernetes version') {
steps {
sh "echo 'Checking Kubernetes version..'"
// How to do remote test of kubernetes version
}
}
stage('Push Helm Charts to Kubernetes') {
steps {
sh "echo 'building..'"
// push here helm chart from Jenkins server to Kubernetes cluster
}
}
stage('Build Image') {
steps {
sh "echo 'building..'"
// configure credentials under http://192.168.1.28:8080/user/test/credentials/ and put credentials ID
git credentialsId: 'bitbucket-server:50001e738fa6dafbbe7e336853ced1fcbc284fb18ea8cda8b54dbfa3a7bc87b9', url: 'http://192.168.1.30:7990/scm/jen/spring-boot-microservice.git', branch: 'master'
// execute Java -jar ... and build docker image
./gradlew build && java -jar build/libs/gs-spring-boot-docker-0.1.0.jar
docker build -t springio/gs-spring-boot-docker .
}
}
stage('Push Image into Nexus registry') {
steps {
sh "echo 'building..'"
// push compiled docker image into Nexus repository
script {
pom = readMavenPom file: "pom.xml";
filesByGlob = findFiles(glob: "target/*.${pom.packaging}");
echo "${filesByGlob[0].name} ${filesByGlob[0].path} ${filesByGlob[0].directory} ${filesByGlob[0].length} ${filesByGlob[0].lastModified}"
artifactPath = filesByGlob[0].path;
artifactExists = fileExists artifactPath;
if(artifactExists) {
echo "*** File: ${artifactPath}, group: ${pom.groupId}, packaging: ${pom.packaging}, version ${pom.version}";
nexusArtifactUploader(
nexusVersion: NEXUS_VERSION,
protocol: NEXUS_PROTOCOL,
nexusUrl: NEXUS_URL,
groupId: pom.groupId,
version: pom.version,
repository: NEXUS_REPOSITORY,
credentialsId: NEXUS_CREDENTIAL_ID,
artifacts: [
[artifactId: pom.artifactId,
classifier: '',
file: artifactPath,
type: pom.packaging],
[artifactId: pom.artifactId,
classifier: '',
file: "pom.xml",
type: "pom"]
]
);
} else {
error "*** File: ${artifactPath}, could not be found";
}
}
}
}
stage('Deploy Image from Nexus registry into Kubernetes') {
steps {
sh "echo 'building..'"
}
}
stage('Test'){
steps {
sh "echo 'Testing...'"
// implement a check here is it deployed sucessfully
}
}
}
}
How I can deploy the docker image build by Jenkins server and pushed in Nexus repository? If possible I want to use service account with token?
Instead of using 'nexusArtifactUploader', why don´t you use docker push, like you do to build the image?
I guess nexusArtifactUploader uses Nexus API and doesn´t work with docker images, but you can access the registry using docker and the exposed port (defaults to 5000)
withCredentials([string(credentialsId: NEXUS_CREDENTIAL_ID, variable: 'registryToken')]) {
sh 'docker push --creds default:${registryToken} your-registry-url/image-name:image-tag'
}
You may also change docker build command to build the image using your registry name (or tag it after building, see How to push a docker image to a private repository)

Jenkins dynamic choice parameter to read a ansible host file in github

I have an ansible host file that is stored in GitHub and was wondering if there is a way to list out all the host in jenkins with choice parameters? Right now every time I update the host file in Github I would have to manually go into each Jenkins job and update the choice parameter manually. Thanks!
I'm assuming your host file has content something similar to below.
[client-app]
client-app-preprod-01.aws-xxxx
client-app-preprod-02.aws
client-app-preprod-03.aws
client-app-preprod-04.aws
[server-app]
server-app-preprod-01.aws
server-app-preprod-02.aws
server-app-preprod-03.aws
server-app-preprod-04.aws
Option 01
You can do something like the one below. Here you can first checkout the repo and then ask for the user input. I have implemented the function getHostList() to parse the host file to filter the host entries.
pipeline {
agent any
stages {
stage('Build') {
steps {
git 'https://github.com/jglick/simple-maven-project-with-tests.git'
script {
def selectedHost = input message: 'Please select the host', ok: 'Next',
parameters: [
choice(name: 'PRODUCT', choices: getHostList("client-app","ansible/host/location"), description: 'Please select the host')]
echo "Host:::: $selectedHost"
}
}
}
}
}
def getHostList(def appName, def filePath) {
def hosts = []
def content = readFile(file: filePath)
def startCollect = false
for(def line : content.split('\n')) {
if(line.contains("["+ appName +"]")){ // This is a starting point of host entries
startCollect = true
continue
} else if(startCollect) {
if(!line.allWhitespace && !line.contains('[')){
hosts.add(line.trim())
} else {
break
}
}
}
return hosts
}
Option 2
If you want to do this without checking out the source and with Job Parameters. You can do something like the one below using the Active Choice Parameter plugin. If your repository is private, you need to figure out a way to generate an access token to access the Raw GitHub link.
properties([
parameters([
[$class: 'ChoiceParameter',
choiceType: 'PT_SINGLE_SELECT',
description: 'Select the Host',
name: 'Host',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: false,
script:
'return [\'Could not get Host\']'
],
script: [
classpath: [],
sandbox: false,
script:
'''
def appName = "client-app"
def content = new URL ("https://raw.githubusercontent.com/xxx/sample/main/testdir/hosts").getText()
def hosts = []
def startCollect = false
for(def line : content.split("\\n")) {
if(line.contains("["+ appName +"]")){ // This is a starting point of host entries
startCollect = true
continue
} else if(startCollect) {
if(!line.allWhitespace && !line.contains("[")){
hosts.add(line.trim())
} else {
break
}
}
}
return hosts
'''
]
]
]
])
])
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
echo "Host:::: ${params.Host}"
}
}
}
}
}
Update
When you are calling a private repo, you need to send a Basic Auth header with the access token. So use the following groovy script instead.
def accessToken = "ACCESS_TOKEN".bytes.encodeBase64().toString()
def get = new URL("https://raw.githubusercontent.com/xxxx/something/hosts").openConnection();
get.setRequestProperty("authorization", "Basic " + accessToken)
def content = get.getInputStream().getText()

I am getting a vmSize error when trying to deploy a batch service pool using bicep

I have the following Bicep code:
resource pool 'Microsoft.Batch/batchAccounts/pools#2021-06-01' = {
name: '${bs.name}/run-python'
properties: {
scaleSettings: {
fixedScale: {
nodeDeallocationOption: 'TaskCompletion'
targetDedicatedNodes: 1
}
}
deploymentConfiguration: {
cloudServiceConfiguration: {
osFamily: '6'
}
}
vmSize: 'standard_A1_v2'
startTask: {
commandLine: 'cmd /c "pip install azure-storage-blob pandas"'
userIdentity: {
autoUser: {
elevationLevel: 'NonAdmin'
scope: 'Pool'
}
}
waitForSuccess: true
}
}
dependsOn: [
bs
]
}
Where I try to create a pool for my batch service, but when I try to deploy it, I get the following error:
{"code":"DeploymentFailed","message":"At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/DeployOperations for usage details.","details":[{"code":"PropertyName","message":"vmSize"}]}
So I think the problem is the vmSize, but there I cannot find concrete example on what the value should be.
CloudServiceConfiguration Pools are deprecated. Please retry using VirtualMachineConfiguration.

How to resolve HttpService.sendRPCRequest ECONNREFUSED error while deploying contract on azure blockchain service using VSCode?

I have created a new consortium on Azure Blockchain Service and set up Visual Studio Code using Azure Blockchain Development Kit extension. I have my consortium set up in VSCode and also created a new solidity project. I compiled/built the default HelloBlockchain smart contract successfully. But when I deployed the contract, it gave me this error:
Get version for required apps: truffle
[Execute command]
Working dir: /home/manul/securevoting/blockchain
Running command
npx truffle migrate --reset --network electionmanagement
[Execute command]
Compiling your contracts...
[Execute command] ===========================
[Execute command] > Everything is up to date, there is nothing to
compile.
[Execute command]
[Execute command] Finished running command
[Azure Blockchain] HttpService.sendRPCRequest has done with error:
RequestError: Error: connect ECONNREFUSED 127.0.0.1:8545
[Azure Blockchain] HttpService.sendRPCRequest has done with error:
RequestError: Error: connect ECONNREFUSED 52.168.92.164:3200
Here is my truffle-config.js:
const HDWalletProvider = require('truffle-hdwallet-provider');
const fs = require('fs');
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 8545,
network_id: "*"
},
electionmanagement: {
network_id: "*",
gas: 0,
gasPrice: 0,
provider: new HDWalletProvider(fs.readFileSync('/home/manul/securevoting/blockchain/administrator.env', 'utf-8'), "https://administrator.blockchain.azure.com:3200/5GJ3H0vdRuvo6AkPDFRRbxL0"),
consortium_id: 1565975083891
}
},
mocha: {},
compilers: {
solc: {
version: "0.5.0"
}
}
};
Here is 2_deploy_contracts.js file in migrations folder:
var HelloBlockchain = artifacts.require("HelloBlockchain");
var Arg = "Hello world";
module.exports = deployer => {
deployer.deploy(HelloBlockchain, Arg);
};
A screenshot of my VSCode Window
Any help would be greatly appreciated.
I was experiencing the same error. I guess the blockchain services are not permitted on your college's wifi/LAN. Just use VPN or Mobile Hotspot, not your college's wifi/LAN.