Firebase Cloud Function deploy functions error: lint: eslint - java

I have followed a tutorial to implement an observe follower notification.
exports.observeFollowing = functions.database.ref('/following/{uid}/{followingId}').onCreate((snapshot, context) => {
var uid = context.params.uid;
var followingId = context.params.followingId;
console.log('User: ' + uid + ' is following: ' + followingId);
return admin.database().ref('/users/' + followingId).once('value', snapshot => {
var userWeAreFollowing = snapshot.val();
return admin.database().ref('/users/' + uid).once('value', snapshot => {
var userDoingTheFollowing = snapshot.val();
var payload = {
notification: {
title: "You now have a new follower",
body: userDoingTheFollowing.username + "is now following you",
sound: 'default'
}
}
admin.messaging().sendToDevice(userWeAreFollowing.fcmToken, payload)
.then((response) => {
console.log('Successfully sent message:', response);
return response;
}).catch(function(error) => {
console.log('Error sending message:', error);
});
})
})
})
However, when I tried to run firebase deploy --only functions:observeFollowing I receive the following error:
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions# lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions# lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
I had tried to search answers from Stackoverflow but none of the answers seen to work.

Related

Jenkins Error : Unknown stage section "stage". Starting with version 0.5, steps in a stage must be in a ‘steps’ block

When i try to build my main in jenkins it gives me the error in the title, even though i checked and this seems like a valid configuration.
This is th code :
pipeline {
agent any
environment {
DOCKER_PASSWORD = credentials("docker_password")
GITHUB_TOKEN = credentials(".....")
}
stages {
stage('Build & Test') {
steps {
sh './gradlew clean build'
}
stage('Tag image') {
steps {
script {
GIT_TAG = sh([script: 'git fetch --tag && git tag', returnStdout: true]).trim()
MAJOR_VERSION = sh([script: 'git tag | cut -d . -f 1', returnStdout: true]).trim()
MINOR_VERSION = sh([script: 'git tag | cut -d . -f 2', returnStdout: true]).trim()
PATCH_VERSION = sh([script: 'git tag | cut -d . -f 3', returnStdout: true]).trim()
}
sh '''
docker build -t tibicode/hello-img:${MAJOR_VERSION}.\$((${MINOR_VERSION} + 1)).${PATCH_VERSION} ."
docker login docker.io -u tibicode -p ........"
docker push <tibicode>/hello-img:$IMAGE_VERSION"
'''
}
}
}
}

Writing a pipelineplugin in Jenkins

I am writing a Jenkinsplugin. I have set up a pipeline script, when I execute the script its calling some shell scripts and setting up a pipeline. Thats working fine.
Example of my code:
node('master') {
try {
def appWorkspace = './app/'
def testWorkspace = './tests/'
stage('Clean up') {
// cleanWs()
}
stage('Build') {
parallel (
app: {
dir(appWorkspace) {
git changelog: false, credentialsId: 'jenkins.git', poll: false, url: 'https://src.url/to/our/repo'
dir('./App') {
sh "#!/bin/bash -lx \n ./gradlew assembleRelease"
}
}
},
tests: {
dir(testWorkspace) {
git changelog: false, credentialsId: 'jenkins.git', poll: false, url: 'https://src.url/to/our/repo'
sh "#!/bin/bash -lx \n nuget restore ./Tests/MyProject/MyProject.sln"
sh "#!/bin/bash -lx \n msbuild ./Tests/MyProject/MyProject.Core/ /p:Configuration=Debug"
}
}
)
}
stage('Prepare') {
parallel (
'install-apk': {
sh '''#!/bin/bash -lx
result="$(adbExtendedVersion shell pm list packages packagename.app)"
if [ ! -z "$result" ]
then
adbExtendedVersion uninstall packagename.app
fi
adbExtendedVersion install ''' + appWorkspace + '''/path/to/app-release.apk'''
},
'start-appium': {
sh "#!/bin/bash -lx \n GetAllAttachedDevices.sh"
sh "sleep 20s"
}
)
}
stage('Test') {
// Reading content of the file
def portsFileContent = readFile 'file.txt'
// Split the file by next line
def ports = portsFileContent.split('\n')
// Getting device IDs to get properties of device
def deviceIDFileContent = readFile 'IDs.txt'
def deviceIDs = deviceIDFileContent.split('\n')
// Define port and id as an pair
def pairs = (0..<Math.min(ports.size(), deviceIDs.size())).collect { i -> [id: deviceIDs[i], port: ports[i]] }
def steps = pairs.collectEntries { pair ->
["UI Test on ${pair.id}", {
sh "#!/bin/bash -lx \n mono $testWorkspace/Tests/packages/NUnit.ConsoleRunner.3.7.0/tools/nunit3-console.exe $testWorkspace/Tests/bin/Debug/MyProject.Core.dll --params=port=${pair.port}"
}]
}
parallel steps
}
}
catch (Exception e) {
println(e);
}
finally {
stage('Clean') {
archiveArtifacts 'TestResult.xml'
sh "#!/bin/bash -lx \n KillInstance.sh"
}
}
}
This is a groovy script defining my pipeline. What I am trying to achieve with my plugin is, that the user who uses this plugin just inserts some pathvariables eg. path to his solution, or path to his github source. My Plugin then executes the above listed script automatically with the given parameters.
My problem is, that I cant find any documentation how to write such a pipeline construct in Java. If someone could point me in the right direction I would appreciate that.

Updating module version when updating version in dependencies (multi-module maven )

My problem: versions-maven-plugin helps me to up version in some module (let's call it A) in my multi-module maven project.
Some modules (let's call it B and C) in this project have in dependencies module A. I need to up versions for this modules (B and C) too. Sometimes, i also need to up version in other module (B-parent) where B (or C) in dependencies (A version up -> B version up -> B-parent version up). Other problem is the modules can be at different levels of nesting.
Example:
root:
---B-parent:
---B (A in dependencies)
---C-parent
---C (A in dependencies)
---A-parent:
---A
Process: A version up -> A-parent version up, C version-up -> C-parent version-up, B version-up -> B-parent version up.
This plugin can't do this.
Is there any idea how this can be done?
Or my strategy of updating versions is not good enough?
I've made a script for increasing version numbers in all dependent modules recursively with a versions-maven-plugin.
Algorithm is as follows:
Run versions:set in target module
Run versions:set in all modules which have been updated by versions:set from previous step. If the module has been already processed - skip it.
Repeat step 2
Python 2.7 code
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
# How To
#
# Run script and pass module path as a first argument.
# Or run it without arguments in module dir.
#
# Script will request the new version number for each module.
# If no version provided - last digit will be incremented (1.0.0 -> 1.0.1).
# cd <module-path>
# <project-dir>/increment-version.py
# ...
# review changes and commit
from subprocess import call, Popen, PIPE, check_output
import os
import re
import sys
getVersionCommand = "mvn org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate " \
"-Dexpression=project.version 2>/dev/null | grep -v '\['"
def getCurrentModuleVersion():
return check_output(getVersionCommand, shell=True).decode("utf-8").split("\n")[0]
def incrementLastDigit(version):
digits = version.split(".")
lastDigit = int(digits[-1])
digits[-1] = str(lastDigit+1)
return ".".join(digits)
def isUpdatedVersionInFile(version, file):
return "<version>" + version + "</version>" in \
check_output("git diff HEAD --no-ext-diff --unified=0 --exit-code -a --no-prefix {} "
"| egrep \"^\\+\"".format(file), shell=True).decode("utf-8")
def runVersionSet(version):
process = Popen(["mvn", "versions:set", "-DnewVersion="+version, "-DgenerateBackupPoms=false"], stdout=PIPE)
(output, err) = process.communicate()
exitCode = process.wait()
if exitCode is not 0:
print "Error setting the version"
exit(1)
return output, err, exitCode
def addChangedPoms(version, dirsToVisit, visitedDirs):
changedFiles = check_output(["git", "ls-files", "-m"]) \
.decode("utf-8").split("\n")
changedPoms = [f for f in changedFiles if f.endswith("pom.xml")]
changedDirs = [os.path.dirname(os.path.abspath(f)) for f in changedPoms if isUpdatedVersionInFile(version, f)]
changedDirs = [d for d in changedDirs if d not in visitedDirs and d not in dirsToVisit]
print "New dirs to visit:", changedDirs
return changedDirs
if __name__ == "__main__":
visitedDirs = []
dirsToVisit = []
if len(sys.argv) > 1:
if os.path.exists(os.path.join(sys.argv[1], "pom.xml")):
dirsToVisit.append(os.path.abspath(sys.argv[1]))
else:
print "Error. No pom.xml file in dir", sys.argv[1]
exit(1)
else:
dirsToVisit.append(os.path.abspath(os.getcwd()))
pattern = re.compile("aggregation root: (.*)")
while len(dirsToVisit) > 0:
dirToVisit = dirsToVisit.pop()
print "Visiting dir", dirToVisit
os.chdir(dirToVisit)
currentVersion = getCurrentModuleVersion()
defaultVersion = incrementLastDigit(currentVersion)
version = raw_input("New version for {}:{} ({}):".format(dirToVisit, currentVersion, defaultVersion))
if not version.strip():
version = defaultVersion
print "New version:", version
output, err, exitcode = runVersionSet(version)
rootDir = pattern.search(output).group(1)
visitedDirs = visitedDirs + [dirToVisit]
os.chdir(rootDir)
print "Adding new dirs to visit"
dirsToVisit = dirsToVisit + addChangedPoms(version, dirsToVisit, visitedDirs)

Firebase Java Admin SDK 5.6.0 FirestoreClient constantly throws io.grpc.StatusRuntimeException: UNKNOWN

When using the Firebase Admin SDK 5.6.0 for Java (in a Scala Play! application), we are constantly getting io.grpc.StatusRuntimeException: UNKNOWN anytime we get or set data using the FirestoreClient. The auth functions of Firebase seem to work without any issue, however.
Here is the exception we are getting:
ERROR application - method=GET uri=/v1/users/synchAllUsers remote-address=0:0:0:0:0:0:0:1 status=500 error=class java.util.concurrent.ExecutionException: io.grpc.StatusRuntimeException: UNKNOWN
com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:503)
com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:482)
com.google.api.core.AbstractApiFuture.get(AbstractApiFuture.java:56)
services.FirebaseAdminService.createToken(FirebaseAdminService.scala:98)
services.UsersService.$anonfun$synchAllUsers$2(UsersService.scala:37)
scala.collection.Iterator.foreach(Iterator.scala:929)
scala.collection.Iterator.foreach$(Iterator.scala:929)
scala.collection.AbstractIterator.foreach(Iterator.scala:1417)
scala.collection.IterableLike.foreach(IterableLike.scala:71)
scala.collection.IterableLike.foreach$(IterableLike.scala:70)
scala.collection.AbstractIterable.foreach(Iterable.scala:54)
services.UsersService.$anonfun$synchAllUsers$1(UsersService.scala:34)
services.UsersService.$anonfun$synchAllUsers$1$adapted(UsersService.scala:34)
scala.util.Success.$anonfun$map$1(Try.scala:251)
scala.util.Success.map(Try.scala:209)
scala.concurrent.Future.$anonfun$map$1(Future.scala:287)
scala.concurrent.impl.Promise.liftedTree1$1(Promise.scala:29)
scala.concurrent.impl.Promise.$anonfun$transform$1(Promise.scala:29)
scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)
akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:55)
akka.dispatch.BatchingExecutor$BlockableBatch.$anonfun$run$1(BatchingExecutor.scala:91)
scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:81)
akka.dispatch.BatchingExecutor$BlockableBatch.run(BatchingExecutor.scala:91)
akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:38)
akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(ForkJoinExecutorConfigurator.scala:43)
akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Here is the code we are running:
private lazy val app = {
FirebaseApp.getApps().stream().filter(a => a.getName == FirebaseApp.DEFAULT_APP_NAME).findFirst().orElseGet(
() => {
//val serviceAccount = new ByteArrayInputStream(Firebase.serviceAccountKey.getBytes(StandardCharsets.UTF_8.name()))
val serviceAccount = new FileInputStream("conf/gcp_service_account.json")
val options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
//.setDatabaseUrl("https://festive-bazaar-146119.firebaseio.com")
.build()
serviceAccount.close()
FirebaseApp.initializeApp(options, FirebaseApp.DEFAULT_APP_NAME)
}
)
}
def createToken(user: User, claims: Map[String, Object] = Map()) = {
val auth = FirebaseAuth.getInstance(app)
val db = FirestoreClient.getFirestore(app)
val firebaseUser = getUserById(auth, user.id.toString)
if (firebaseUser == null) {
auth.createUserAsync(new CreateRequest()
.setUid(user.id.toString)
.setDisplayName(user.firstName + ' ' + user.lastName)
.setEmail(user.email)
.setEmailVerified(true)
.setDisabled(false)).get()
}
else {
auth.updateUserAsync(new UpdateRequest(user.id.toString)
.setDisplayName(user.firstName + ' ' + user.lastName)
.setEmail(user.email)
.setEmailVerified(true)
.setDisabled(false)).get()
}
// Set the user's info in our user metadata area
val userInfoRec = new ImmutableMap.Builder[String, String]()
.put("id", user.id.toString)
.put("name", user.email)
.put("email", user.email)
.put("firstName", user.firstName)
.put("lastName", user.lastName)
.build()
db.collection("tenants").document(user.companyId.toString).collection("users").document(user.id.toString).get()
val users = db.collection("tenants").get.get
val result = db.collection("tenants").document(user.companyId.toString).collection("users").document(user.id.toString).set(userInfoRec)
result.get() // **** This triggers the exception shown above, everytime ****
auth.createCustomTokenAsync(user.id.toString, (claims + ("companyId" -> user.companyId.asInstanceOf[Object])).asJava).get()
}
The comment above with the **** notes that is the line that triggers the exception. Has anyone else run into this problem or knows anything about this? In its current state, it makes the FirestoreClient completely useless to us as we can neither get or set data to the Firestore. I've checked the documentation, API reference, and generally Googled around but can't seem to find anything useful.

Why zabbix do not show a value received from java code?

Consider a java code:
String host = "zabbixHost";
int port = 10051;
ZabbixSender zabbixSender = new ZabbixSender(host, port);
DataObject dataObject = new DataObject();
dataObject.setHost("testHost");
dataObject.setKey("test.ping.count");
dataObject.setValue("10");
// TimeUnit is SECONDS.
dataObject.setClock(System.currentTimeMillis()/1000);
SenderResult result = zabbixSender.send(dataObject);
System.out.println("result:" + result);
if (result.success()) {
System.out.println("send success.");
} else {
System.err.println("sned fail!");
}
The result is {"failed":0,"processed":1,"spentSeconds":0.001715,"total":1}
Then I send a request by zabbix_sender tool from command line:
zabbix_sender -z zabbixHost -p 10051 -s testHost -k test.ping.count -o 8 -v
The output is:
info from server: "processed: 1; failed: 0; total: 1; seconds spent: 0.002052"
sent: 1; skipped: 0; total: 1
For now 2 values were sent into Zabbix. But when I got to the monitoring graphic for test.ping.count and only 8 value is shown. E.g. value from java code was not received even when response was successful.
What is going on? How to fix such situation?
Note
The library is - io.github.hengyunabc:zabbix-sender:0.0.3
Zabbix version is 3.0
The problem was with timestamps, zabbix-sender with version 0.0.1 set request (not dataobject) clock in milliseconds while version 0.0.3 in seconds. So using right version fix issues.
maven sample (source):
<dependency>
<groupId>io.github.hengyunabc</groupId>
<artifactId>zabbix-sender</artifactId>
<version>0.0.3</version>
</dependency>

Categories

Resources