Skip to content

Commit

Permalink
update ktlint, add .editorconfig (jitsi#310)
Browse files Browse the repository at this point in the history
* update ktlint, add .editorconfig

* remove unused helper function

* fix linter errors
  • Loading branch information
bbaldino authored Jul 2, 2020
1 parent 6c5b06d commit 3e98db8
Show file tree
Hide file tree
Showing 31 changed files with 118 additions and 83 deletions.
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[*.{kt,kts}]
# Comma-separated list of rules to disable (Since 0.34.0)
# Note that rules in any ruleset other than the standard ruleset will need to be prefixed
# by the ruleset identifier.
# intellij currently has no setting to set sort order, and its
# default behavior directly contradicts what this rule wants. see
# https://youtrack.jetbrains.com/issue/KT-10974
disabled_rules=import-ordering
max_line_length=120
29 changes: 24 additions & 5 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -303,12 +303,31 @@
<version>1.8</version>
<executions>
<execution>
<id>ktlint-and-autoformat</id>
<phase>compile</phase>
<id>ktlint</id>
<phase>verify</phase>
<configuration>
<skip>${ktlint.skip}</skip>
<target name="ktlint">
<java taskname="ktlint" dir="${basedir}" fork="true" failonerror="true"
classpathref="maven.plugin.classpath" classname="com.pinterest.ktlint.Main">
<arg value="src/**/*.kt"/>
<!-- to generate report in checkstyle format prepend following args: -->
<!--
<arg value="[dash][dash]reporter=plain"/>
<arg value="[dash][dash]reporter=checkstyle,output=${project.build.directory}/ktlint.xml"/>
-->
<!-- see https://github.com/shyiko/ktlint#usage for more -->
</java>
</target>
</configuration>
<goals><goal>run</goal></goals>
</execution>
<execution>
<id>ktlint-format</id>
<configuration>
<target name="ktlint">
<java taskname="ktlint" dir="${basedir}" fork="true" failonerror="true"
classpathref="maven.plugin.classpath" classname="com.github.shyiko.ktlint.Main">
classpathref="maven.plugin.classpath" classname="com.pinterest.ktlint.Main">
<arg value="-F"/>
<arg value="src/**/*.kt"/>
</java>
Expand All @@ -319,9 +338,9 @@
</executions>
<dependencies>
<dependency>
<groupId>com.github.shyiko</groupId>
<groupId>com.pinterest</groupId>
<artifactId>ktlint</artifactId>
<version>0.20.0</version>
<version>0.36.0</version>
</dependency>
<!-- additional 3rd party ruleset(s) can be specified here -->
</dependencies>
Expand Down
15 changes: 8 additions & 7 deletions src/main/kotlin/org/jitsi/jibri/JibriManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -220,14 +220,15 @@ class JibriManager(
currentEnvironmentContext = environmentContext
if (serviceParams.usageTimeoutMinutes != 0) {
logger.info("This service will have a usage timeout of ${serviceParams.usageTimeoutMinutes} minute(s)")
serviceTimeoutTask = TaskPools.recurringTasksPool.schedule(serviceParams.usageTimeoutMinutes.toLong(), TimeUnit.MINUTES) {
logger.info("The usage timeout has elapsed, stopping the currently active service")
try {
stopService()
} catch (t: Throwable) {
logger.error("Error while stopping service due to usage timeout: $t")
serviceTimeoutTask =
TaskPools.recurringTasksPool.schedule(serviceParams.usageTimeoutMinutes.toLong(), TimeUnit.MINUTES) {
logger.info("The usage timeout has elapsed, stopping the currently active service")
try {
stopService()
} catch (t: Throwable) {
logger.error("Error while stopping service due to usage timeout: $t")
}
}
}
}
TaskPools.ioPool.submit {
jibriService.start()
Expand Down
25 changes: 19 additions & 6 deletions src/main/kotlin/org/jitsi/jibri/api/http/HttpApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -109,30 +109,43 @@ class HttpApi(
return when (startServiceParams.sinkType) {
RecordingSinkType.FILE -> {
// If it's a file recording, it must have the callLoginParams set
val callLoginParams = startServiceParams.callLoginParams ?: return Response.status(Response.Status.PRECONDITION_FAILED).build()
val callLoginParams = startServiceParams.callLoginParams
?: return Response.status(Response.Status.PRECONDITION_FAILED).build()
serviceLauncher {
jibriManager.startFileRecording(
ServiceParams(usageTimeoutMinutes = 0),
FileRecordingRequestParams(startServiceParams.callParams, startServiceParams.sessionId, callLoginParams),
FileRecordingRequestParams(
startServiceParams.callParams,
startServiceParams.sessionId,
callLoginParams
),
environmentContext = null
)
}
}
RecordingSinkType.STREAM -> {
val youTubeStreamKey = startServiceParams.youTubeStreamKey ?: return Response.status(Response.Status.PRECONDITION_FAILED).build()
val youTubeStreamKey = startServiceParams.youTubeStreamKey
?: return Response.status(Response.Status.PRECONDITION_FAILED).build()
// If it's a stream, it must have the callLoginParams set
val callLoginParams = startServiceParams.callLoginParams ?: return Response.status(Response.Status.PRECONDITION_FAILED).build()
val callLoginParams = startServiceParams.callLoginParams
?: return Response.status(Response.Status.PRECONDITION_FAILED).build()
serviceLauncher {
jibriManager.startStreaming(
ServiceParams(usageTimeoutMinutes = 0),
StreamingParams(startServiceParams.callParams, startServiceParams.sessionId, callLoginParams, youTubeStreamKey),
StreamingParams(
startServiceParams.callParams,
startServiceParams.sessionId,
callLoginParams,
youTubeStreamKey
),
environmentContext = null
)
}
}
RecordingSinkType.GATEWAY -> {
// If it's a sip gateway, it must have sipClientParams set
val sipClientParams = startServiceParams.sipClientParams ?: return Response.status(Response.Status.PRECONDITION_FAILED).build()
val sipClientParams = startServiceParams.sipClientParams
?: return Response.status(Response.Status.PRECONDITION_FAILED).build()
serviceLauncher {
jibriManager.startSipGateway(
ServiceParams(usageTimeoutMinutes = 0),
Expand Down
12 changes: 9 additions & 3 deletions src/main/kotlin/org/jitsi/jibri/api/xmpp/XmppApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,12 @@ class XmppApi(
disableCertificateVerification = config.trustAllXmppCerts
}

val recordingMucJid = JidCreate.bareFrom("${config.controlMuc.roomName}@${config.controlMuc.domain}").toString()
val recordingMucJid =
JidCreate.bareFrom("${config.controlMuc.roomName}@${config.controlMuc.domain}").toString()
val sipMucJid: String? = config.sipControlMuc?.let {
JidCreate.entityBareFrom("${config.sipControlMuc.roomName}@${config.sipControlMuc.domain}").toString()
JidCreate.entityBareFrom(
"${config.sipControlMuc.roomName}@${config.sipControlMuc.domain}"
).toString()
}
mucJids = listOfNotNull(recordingMucJid, sipMucJid)
mucNickname = config.controlMuc.nickname
Expand Down Expand Up @@ -156,7 +159,10 @@ class XmppApi(
private fun handleJibriIq(jibriIq: JibriIq, mucClient: MucClient): IQ {
logger.info("Received JibriIq ${jibriIq.toXML()} from environment $mucClient")
val xmppEnvironment = xmppConfigs.find { it.xmppServerHosts.contains(mucClient.id) }
?: return IQ.createErrorResponse(jibriIq, XMPPError.getBuilder().setCondition(XMPPError.Condition.bad_request))
?: return IQ.createErrorResponse(
jibriIq,
XMPPError.getBuilder().setCondition(XMPPError.Condition.bad_request)
)
return when (jibriIq.action) {
JibriIq.Action.START -> handleStartJibriIq(jibriIq, xmppEnvironment, mucClient)
JibriIq.Action.STOP -> handleStopJibriIq(jibriIq)
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/org/jitsi/jibri/capture/ffmpeg/Errors.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ class BadRtmpUrl(outputLine: String) : FfmpegError(ErrorScope.SESSION, outputLin
override fun shouldRetry(): Boolean = false
}
class BrokenPipe(outputLine: String) : FfmpegError(ErrorScope.SESSION, outputLine)
class QuitUnexpectedly(outputLine: String) : FfmpegError(ErrorScope.SESSION, outputLine)
class QuitUnexpectedly(outputLine: String) : FfmpegError(ErrorScope.SESSION, outputLine)
2 changes: 1 addition & 1 deletion src/main/kotlin/org/jitsi/jibri/error/JibriError.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ open class JibriError(
) {
open fun shouldRetry(): Boolean = true
override fun toString(): String = "Error: ${this::class.java.simpleName} $scope $detail"
}
}
2 changes: 1 addition & 1 deletion src/main/kotlin/org/jitsi/jibri/selenium/Errors.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ import org.jitsi.jibri.status.ErrorScope

object FailedToJoinCall : JibriError(ErrorScope.SESSION, "Failed to join the call")
object ChromeHung : JibriError(ErrorScope.SESSION, "Chrome hung")
object NoMediaReceived : JibriError(ErrorScope.SESSION, "No media received")
object NoMediaReceived : JibriError(ErrorScope.SESSION, "No media received")
3 changes: 2 additions & 1 deletion src/main/kotlin/org/jitsi/jibri/selenium/JibriSelenium.kt
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,8 @@ class JibriSelenium(
"callStatsUserName" to "jibri"
)
xmppCredentials?.let {
localStorageValues["xmpp_username_override"] = "${xmppCredentials.username}@${xmppCredentials.domain}"
localStorageValues["xmpp_username_override"] =
"${xmppCredentials.username}@${xmppCredentials.domain}"
localStorageValues["xmpp_password_override"] = xmppCredentials.password
}
setLocalStorageValues(localStorageValues)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,4 @@ class SeleniumStateMachine : NotifyingStateMachine() {
}

fun transition(event: SeleniumEvent): StateMachine.Transition<*, *, *> = stateMachine.transition(event)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,4 @@ class StateTransitionTimeTracker(private val clock: Clock) {
Duration.between(it, clock.instant()) > timeout
} ?: false
}
}
}
2 changes: 2 additions & 0 deletions src/main/kotlin/org/jitsi/jibri/service/Errors.kt
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// ktlint-disable filename

/*
* Copyright @ 2018 - present 8x8, Inc.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,9 @@ class JibriServiceStateMachine : NotifyingStateMachine() {
private val subComponentStates = mutableMapOf<String, ComponentState>()

fun registerSubComponent(componentKey: String) {
//TODO: we'll assume everything starts in 'starting up' ?
// TODO: we'll assume everything starts in 'starting up' ?
subComponentStates[componentKey] = ComponentState.StartingUp
}

fun transition(event: JibriServiceEvent): StateMachine.Transition<*, *, *> = stateMachine.transition(event)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,8 @@ class FileRecordingJibriService(
publishStatus(ComponentState.Error(CouldntWriteMeetingMetadata))
}
} else {
logger.error("Unable to write metadata file to recording directory ${fileRecordingParams.recordingDirectory}")
logger.error("Unable to write metadata file to recording directory " +
"${fileRecordingParams.recordingDirectory}")
}
jibriSelenium.leaveCallAndQuitBrowser()
logger.info("Finalizing the recording")
Expand Down Expand Up @@ -227,4 +228,4 @@ class FileRecordingJibriService(

object ErrorCreatingRecordingsDirectory : JibriError(ErrorScope.SYSTEM, "Could not creat recordings director")
object RecordingsDirectoryNotWritable : JibriError(ErrorScope.SYSTEM, "Recordings directory is not writable")
object CouldntWriteMeetingMetadata : JibriError(ErrorScope.SYSTEM, "Could not write meeting metadata")
object CouldntWriteMeetingMetadata : JibriError(ErrorScope.SYSTEM, "Could not write meeting metadata")
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,4 @@ abstract class StatefulJibriService(private val name: String) : JibriService() {
stateMachine.transition(stateUpdate.toJibriServiceEvent(subComponentId))
}
}
}
}
11 changes: 7 additions & 4 deletions src/main/kotlin/org/jitsi/jibri/sipgateway/pjsua/PjsuaClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,16 @@ class PjsuaClient(private val pjsuaClientParams: PjsuaClientParams) : SipClient(
when {
processState.runningState is ProcessExited -> {
when (processState.runningState.exitCode) {
//TODO: add detail?
// TODO: add detail?
// Remote side hung up
0 -> publishStatus(ComponentState.Finished)
2 -> publishStatus(ComponentState.Error(RemoteSipClientBusy))
else -> publishStatus(ComponentState.Error(PjsuaExitedPrematurely(processState.runningState.exitCode)))
else -> publishStatus(ComponentState.Error(
PjsuaExitedPrematurely(processState.runningState.exitCode))
)
}
}
//TODO: i think everything else just counts as running?
// TODO: i think everything else just counts as running?
else -> publishStatus(ComponentState.Running)
}
}
Expand All @@ -64,7 +66,8 @@ class PjsuaClient(private val pjsuaClientParams: PjsuaClientParams) : SipClient(

if (pjsuaClientParams.sipClientParams.userName != null &&
pjsuaClientParams.sipClientParams.password != null) {
command.add("--id=${pjsuaClientParams.sipClientParams.displayName} <sip:${pjsuaClientParams.sipClientParams.userName}>")
command.add("--id=${pjsuaClientParams.sipClientParams.displayName} " +
"<sip:${pjsuaClientParams.sipClientParams.userName}>")
command.add("--registrar=sip:${pjsuaClientParams.sipClientParams.userName.substringAfter('@')}")
command.add("--realm=*")
command.add("--username=${pjsuaClientParams.sipClientParams.userName.substringBefore('@')}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@ import org.jitsi.jibri.status.ErrorScope
object RemoteSipClientBusy : JibriError(ErrorScope.SESSION, "Remote side busy")

class PjsuaExitedPrematurely(exitCode: Int) :
JibriError(ErrorScope.SESSION, "Pjsua exited with code $exitCode")
JibriError(ErrorScope.SESSION, "Pjsua exited with code $exitCode")
2 changes: 1 addition & 1 deletion src/main/kotlin/org/jitsi/jibri/status/ComponentStates.kt
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,4 @@ enum class ErrorScope {
* [SYSTEM] errors are unrecoverable, and will put Jibri in an unhealthy state
*/
SYSTEM
}
}
3 changes: 2 additions & 1 deletion src/main/kotlin/org/jitsi/jibri/util/JibriSubprocess.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ class JibriSubprocess(
private val name: String,
private val processOutputLogger: Logger? = null,
private val processFactory: ProcessFactory = ProcessFactory(),
private val processStatePublisherProvider: (ProcessWrapper) -> ProcessStatePublisher = { process -> ProcessStatePublisher(name, process) }
private val processStatePublisherProvider: (ProcessWrapper) -> ProcessStatePublisher =
{ process -> ProcessStatePublisher(name, process) }
) : StatusPublisher<ProcessState>() {
private val logger = Logger.getLogger("${this::class.qualifiedName}.$name")
private var processLoggerTask: Future<Boolean>? = null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ abstract class NotifyingStateMachine {
fun onStateTransition(handler: (ComponentState, ComponentState) -> Unit) {
stateTranstionHandlers.add(handler)
}
}
}
3 changes: 1 addition & 2 deletions src/main/kotlin/org/jitsi/jibri/util/ProcessState.kt
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,8 @@ sealed class AliveState(val runningStatus: RunningStatus) {
class ProcessRunning : AliveState(RunningStatus.RUNNING)

class ProcessExited(val exitCode: Int) : AliveState(RunningStatus.EXITED) {
override fun toString(): String = with (StringBuffer()) {
override fun toString(): String = buildString {
append("${super.toString()} exit code: $exitCode")
toString()
}
}

Expand Down
22 changes: 11 additions & 11 deletions src/main/kotlin/org/jitsi/jibri/util/ProcessStatePublisher.kt
Original file line number Diff line number Diff line change
Expand Up @@ -97,16 +97,16 @@ class ProcessStatePublisher(

fun stop() {
recurringProcessAliveTask?.cancel(true)
//TODO: not calling 'tail.stop()' results in us processing ffmpeg's--for example--successful
// exit, which causes a 'finished' state update to propagate up and results in a duplicate 'stopService'
// call in JibriManager, since we have to call stopService after we receive finish (to handle the case
// of the service detecting an empty call, for example) and we can't distinguish a 'finished' state
// from an actual jibri service finishing on its own and the one that results from any call to
// 'stop' when ffmpeg exits. Calling 'tail.stop()' here fixes that behavior, but, i don't
// think that's what we want to do: instead we should be processing every log message a process
// writes to ensure that it exits correctly. In addition to that, we should technically be modeling
// the 'stop' flow differently to be something more like: tell everything to stop and then *ensure*
// it all stopped cleanly and correctly and, if anything didn't, log an error (and perhaps update
// the health state)
// TODO: not calling 'tail.stop()' results in us processing ffmpeg's--for example--successful
// exit, which causes a 'finished' state update to propagate up and results in a duplicate 'stopService'
// call in JibriManager, since we have to call stopService after we receive finish (to handle the case
// of the service detecting an empty call, for example) and we can't distinguish a 'finished' state
// from an actual jibri service finishing on its own and the one that results from any call to
// 'stop' when ffmpeg exits. Calling 'tail.stop()' here fixes that behavior, but, i don't
// think that's what we want to do: instead we should be processing every log message a process
// writes to ensure that it exits correctly. In addition to that, we should technically be modeling
// the 'stop' flow differently to be something more like: tell everything to stop and then *ensure*
// it all stopped cleanly and correctly and, if anything didn't, log an error (and perhaps update
// the health state)
}
}
2 changes: 1 addition & 1 deletion src/main/kotlin/org/jitsi/jibri/util/StateUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,4 @@ class ComponentStateTransitioner(private val statusPublisher: StatusPublisher<Co
}

fun whenever(statusPublisher: StatusPublisher<ComponentState>): ComponentStateTransitioner =
ComponentStateTransitioner(statusPublisher)
ComponentStateTransitioner(statusPublisher)
2 changes: 1 addition & 1 deletion src/main/kotlin/org/jitsi/jibri/util/Tail.kt
Original file line number Diff line number Diff line change
Expand Up @@ -91,4 +91,4 @@ class PublishingTail(
get() {
return tailLogic.mostRecentLine
}
}
}
2 changes: 1 addition & 1 deletion src/main/kotlin/org/jitsi/jibri/util/TaskPools.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,4 @@ class TaskPools {
var ioPool: ExecutorService = DefaultIoPool
var recurringTasksPool: ScheduledExecutorService = DefaultRecurringTaskPool
}
}
}
Loading

0 comments on commit 3e98db8

Please sign in to comment.