Skip to content

Commit

Permalink
✨ Show elapsed on builder page (#257)
Browse files Browse the repository at this point in the history
  • Loading branch information
tosone authored Dec 9, 2023
1 parent 6fec716 commit 643d413
Show file tree
Hide file tree
Showing 15 changed files with 75 additions and 91 deletions.
6 changes: 3 additions & 3 deletions pkg/builder/docker/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func (i instance) Start(ctx context.Context, builderConfig builder.BuilderConfig
builderService := i.builderServiceFactory.New()
err = builderService.UpdateRunner(ctx, builderConfig.BuilderID, builderConfig.RunnerID, map[string]any{
query.BuilderRunner.Status.ColumnName().String(): enums.BuildStatusBuilding,
query.BuilderRunner.StartedAt.ColumnName().String(): time.Now(),
query.BuilderRunner.StartedAt.ColumnName().String(): time.Now().UnixMilli(),
})
if err != nil {
return fmt.Errorf("Update runner status failed: %v", err)
Expand All @@ -134,8 +134,8 @@ func (i instance) Stop(ctx context.Context, builderID, runnerID int64) error {
}
builderService := i.builderServiceFactory.New()
err := builderService.UpdateRunner(ctx, builderID, runnerID, map[string]any{
query.BuilderRunner.Status.ColumnName().String(): status,
query.BuilderRunner.StartedAt.ColumnName().String(): time.Now(),
query.BuilderRunner.Status.ColumnName().String(): status,
query.BuilderRunner.EndedAt.ColumnName().String(): time.Now().UnixMilli(),
})
if err != nil {
log.Error().Err(err).Msg("Update runner status failed")
Expand Down
8 changes: 4 additions & 4 deletions pkg/builder/docker/informer.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,13 +113,13 @@ func (i *instance) informer(ctx context.Context) {
if container.ContainerJSONBase.State.ExitCode == 0 {
updates = map[string]any{
query.BuilderRunner.Status.ColumnName().String(): enums.BuildStatusSuccess,
query.BuilderRunner.EndedAt.ColumnName().String(): time.Now(),
query.BuilderRunner.EndedAt.ColumnName().String(): time.Now().UnixMilli(),
}
log.Info().Str("id", event.Actor.ID).Str("name", container.ContainerJSONBase.Name).Msg("Builder container succeed")
} else {
updates = map[string]any{
query.BuilderRunner.Status.ColumnName().String(): enums.BuildStatusFailed,
query.BuilderRunner.EndedAt.ColumnName().String(): time.Now(),
query.BuilderRunner.EndedAt.ColumnName().String(): time.Now().UnixMilli(),
}
log.Error().Int("ExitCode", container.ContainerJSONBase.State.ExitCode).
Str("Error", container.ContainerJSONBase.State.Error).
Expand Down Expand Up @@ -212,13 +212,13 @@ func (i *instance) cacheList(ctx context.Context) error {
if con.ContainerJSONBase.State.ExitCode == 0 {
updates = map[string]any{
query.BuilderRunner.Status.ColumnName().String(): enums.BuildStatusSuccess,
query.BuilderRunner.EndedAt.ColumnName().String(): time.Now(),
query.BuilderRunner.EndedAt.ColumnName().String(): time.Now().UnixMilli(),
}
log.Info().Str("id", container.ID).Str("name", con.ContainerJSONBase.Name).Msg("Builder container succeed")
} else {
updates = map[string]any{
query.BuilderRunner.Status.ColumnName().String(): enums.BuildStatusFailed,
query.BuilderRunner.EndedAt.ColumnName().String(): time.Now(),
query.BuilderRunner.EndedAt.ColumnName().String(): time.Now().UnixMilli(),
}
log.Error().Int("ExitCode", con.ContainerJSONBase.State.ExitCode).
Str("Error", con.ContainerJSONBase.State.Error).
Expand Down
4 changes: 2 additions & 2 deletions pkg/dal/migrations/mysql/0001_initialize.up.sql
Original file line number Diff line number Diff line change
Expand Up @@ -671,8 +671,8 @@ CREATE TABLE IF NOT EXISTS `builder_runners` (
`raw_tag` varchar(255) NOT NULL,
`description` varchar(255),
`scm_branch` varchar(255),
`started_at` timestamp,
`ended_at` timestamp,
`started_at` bigint,
`ended_at` bigint,
`duration` bigint,
-- other fields
`created_at` bigint NOT NULL DEFAULT (UNIX_TIMESTAMP (CURRENT_TIMESTAMP()) * 1000),
Expand Down
4 changes: 2 additions & 2 deletions pkg/dal/migrations/postgresql/0001_initialize.up.sql
Original file line number Diff line number Diff line change
Expand Up @@ -862,8 +862,8 @@ CREATE TABLE IF NOT EXISTS "builder_runners" (
"raw_tag" varchar(255) NOT NULL,
"description" varchar(255),
"scm_branch" varchar(255),
"started_at" timestamp,
"ended_at" timestamp,
"started_at" bigint,
"ended_at" bigint,
"duration" bigint,
-- other fields
"created_at" bigint NOT NULL DEFAULT ((EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000)::bigint),
Expand Down
4 changes: 2 additions & 2 deletions pkg/dal/migrations/sqlite3/0001_initialize.up.sql
Original file line number Diff line number Diff line change
Expand Up @@ -768,8 +768,8 @@ CREATE TABLE IF NOT EXISTS `builder_runners` (
`raw_tag` varchar(255) NOT NULL, -- image tag
`description` varchar(255),
`scm_branch` varchar(255),
`started_at` timestamp,
`ended_at` timestamp,
`started_at` integer,
`ended_at` integer,
`duration` integer,
-- other fields
`created_at` integer NOT NULL DEFAULT (unixepoch () * 1000),
Expand Down
13 changes: 8 additions & 5 deletions pkg/dal/models/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package models

import (
"fmt"
"time"

"gorm.io/gorm"
Expand Down Expand Up @@ -90,8 +91,8 @@ type BuilderRunner struct {
Description *string
ScmBranch *string

StartedAt *time.Time
EndedAt *time.Time
StartedAt *int64
EndedAt *int64
Duration *int64

Builder Builder
Expand All @@ -103,6 +104,8 @@ func (b *BuilderRunner) AfterUpdate(tx *gorm.DB) error {
return nil
}

fmt.Printf("107: %+v\n", b)

var runnerObj BuilderRunner
err := tx.Model(&BuilderRunner{}).Where("id = ?", b.ID).First(&runnerObj).Error
if err != nil {
Expand All @@ -114,11 +117,11 @@ func (b *BuilderRunner) AfterUpdate(tx *gorm.DB) error {
}

if runnerObj.StartedAt != nil && runnerObj.EndedAt != nil {
var duration = runnerObj.EndedAt.Sub(ptr.To(runnerObj.StartedAt))
var duration = ptr.To(runnerObj.EndedAt) - ptr.To(runnerObj.StartedAt)
err = tx.Model(&BuilderRunner{}).Where("id = ?", b.ID).Updates(
map[string]any{
"duration": duration.Milliseconds(),
"id": b.ID,
"duration": duration,
"id": b.ID, // here will trigger the after update hook, so the id is needed
}).Error
if err != nil {
return err
Expand Down
12 changes: 6 additions & 6 deletions pkg/dal/query/builder_runners.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 2 additions & 10 deletions pkg/handlers/builders/builders_runner_get.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,6 @@ func (h *handler) GetRunner(c echo.Context) error {
return xerrors.NewHTTPError(c, xerrors.HTTPErrCodeInternalError, "Get builder by id failed")
}

var startedAt, endedAt string
if runnerObj.StartedAt != nil {
startedAt = runnerObj.StartedAt.Format(consts.DefaultTimePattern)
}
if runnerObj.EndedAt != nil {
endedAt = runnerObj.EndedAt.Format(consts.DefaultTimePattern)
}

var duration *string
if runnerObj.Duration != nil {
duration = ptr.Of(durafmt.ParseShort(time.Millisecond * time.Duration(ptr.To(runnerObj.Duration))).String())
Expand All @@ -97,8 +89,8 @@ func (h *handler) GetRunner(c echo.Context) error {
Description: runnerObj.Description,
ScmBranch: runnerObj.ScmBranch,

StartedAt: ptr.Of(startedAt),
EndedAt: ptr.Of(endedAt),
StartedAt: runnerObj.StartedAt,
EndedAt: runnerObj.EndedAt,
RawDuration: runnerObj.Duration,
Duration: duration,

Expand Down
12 changes: 2 additions & 10 deletions pkg/handlers/builders/builders_runners_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,6 @@ func (h *handler) ListRunners(c echo.Context) error {
}
var resp = make([]any, 0, len(runnerObjs))
for _, runnerObj := range runnerObjs {
var startedAt, endedAt string
if runnerObj.StartedAt != nil {
startedAt = runnerObj.StartedAt.Format(consts.DefaultTimePattern)
}
if runnerObj.EndedAt != nil {
endedAt = runnerObj.EndedAt.Format(consts.DefaultTimePattern)
}

var duration *string
if runnerObj.Duration != nil {
duration = ptr.Of(durafmt.ParseShort(time.Millisecond * time.Duration(ptr.To(runnerObj.Duration))).String())
Expand All @@ -95,8 +87,8 @@ func (h *handler) ListRunners(c echo.Context) error {
Description: runnerObj.Description,
ScmBranch: runnerObj.ScmBranch,

StartedAt: ptr.Of(startedAt),
EndedAt: ptr.Of(endedAt),
StartedAt: runnerObj.StartedAt,
EndedAt: runnerObj.EndedAt,
RawDuration: runnerObj.Duration,
Duration: duration,

Expand Down
4 changes: 2 additions & 2 deletions pkg/types/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,8 @@ type BuilderRunnerItem struct {
Description *string `json:"description" example:"description"`
ScmBranch *string `json:"scm_branch" example:"main"`

StartedAt *string `json:"started_at" example:"2006-01-02 15:04:05"`
EndedAt *string `json:"ended_at" example:"2006-01-02 15:04:05"`
StartedAt *int64 `json:"started_at" example:"1702128050507"`
EndedAt *int64 `json:"ended_at" example:"1702128050507"`
RawDuration *int64 `json:"raw_duration" example:"10"`
Duration *string `json:"duration" example:"1h"`

Expand Down
6 changes: 3 additions & 3 deletions pkg/types/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ package types

// CreateCacheRequest ...
type CreateCacheRequest struct {
BuilderID int64 `json:"builder_id" path:"builder_id" validate:"required,number" example:"10"`
BuilderID int64 `json:"builder_id" param:"builder_id" validate:"required,number" example:"10"`
}

// DeleteCacheRequest ...
type DeleteCacheRequest struct {
BuilderID int64 `json:"builder_id" path:"builder_id" validate:"required,number" example:"10"`
BuilderID int64 `json:"builder_id" param:"builder_id" validate:"required,number" example:"10"`
}

// GetCacheRequest ...
type GetCacheRequest struct {
BuilderID int64 `json:"builder_id" path:"builder_id" validate:"required,number" example:"10"`
BuilderID int64 `json:"builder_id" param:"builder_id" validate:"required,number" example:"10"`
}
4 changes: 2 additions & 2 deletions web/src/interfaces/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,8 +298,8 @@ export interface IBuilderRunnerItem {
description?: string;
scm_branch?: string;

started_at?: string;
ended_at?: string;
started_at?: number;
ended_at?: number;
raw_duration?: number;
duration?: string;

Expand Down
23 changes: 19 additions & 4 deletions web/src/pages/Builder/RunnerList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ export default function ({ localServer }: { localServer: string }) {
const [page, setPage] = useState(1);
const [total, setTotal] = useState(0);

const [branchText, setBranchText] = useState("");
const [branchTextValid, setBranchTextValid] = useState(true);
useEffect(() => { branchText != "" && setBranchTextValid(/^[a-zA-Z0-9_-]{1,64}$/.test(branchText)) }, [branchText]);

useEffect(() => {
axios.get(localServer + `/api/v1/namespaces/${namespaceId}/repositories/${repository_id}`).then(response => {
if (response?.status === 200) {
Expand All @@ -53,6 +57,7 @@ export default function ({ localServer }: { localServer: string }) {
if (r.builder !== undefined && r.builder !== null) {
setBuilderObj(r.builder);
}
setBranchText(r.builder?.scm_branch || "");
} else {
const errorcode = response.data as IHTTPError;
Toast({ level: "warning", title: errorcode.title, message: errorcode.description });
Expand Down Expand Up @@ -83,13 +88,20 @@ export default function ({ localServer }: { localServer: string }) {
setTagTemplateTextValid(false);
});
}, [tagTemplateText]);
const [branchText, setBranchText] = useState("");
const [branchTextValid, setBranchTextValid] = useState(true);
useEffect(() => { branchText != "" && setBranchTextValid(/^[a-zA-Z0-9_-]{1,64}$/.test(branchText)) }, [branchText]);

const [descriptionText, setDescriptionText] = useState("");
const [descriptionTextValid, setDescriptionTextValid] = useState(true);
useEffect(() => { descriptionText != "" && setDescriptionTextValid(/^.{0,50}$/.test(descriptionText)) }, [descriptionText]);

useEffect(() => {
if (repositoryObj != undefined) {
let tag = localStorage.getItem(`${repositoryObj?.name}-tag`);
if (tag != null) {
setTagTemplateText(tag);
}
}
}, [repositoryObj]);

const createRunner = () => {
if (builderObj == undefined) {
return;
Expand All @@ -111,6 +123,9 @@ export default function ({ localServer }: { localServer: string }) {
if (descriptionText !== "") {
data["description"] = descriptionText;
}
if (repositoryObj != undefined && repositoryObj?.name != "") {
localStorage.setItem(`${repositoryObj?.name}-tag`, `${tagTemplateText}`);
}
axios.post(localServer + `/api/v1/namespaces/${repositoryObj?.namespace_id}/repositories/${repository_id}/builders/${builderObj.id}/runners/run`, data).then(response => {
if (response?.status === 201) {
let data = response.data as IRunOrRerunRunnerResponse;
Expand Down Expand Up @@ -219,7 +234,7 @@ export default function ({ localServer }: { localServer: string }) {
{
builderObj === undefined ? null : (
<button className="my-auto px-4 py-2 h-10 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-purple-600 hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500 sm:order-1 sm:ml-3"
onClick={() => { navigate(`/builders/setup/${repositoryObj?.builder?.id}?namespace=${namespace}&namespace_id=${repositoryObj?.namespace_id}&repository=${repositoryObj?.name}&repository_id=${repositoryObj?.id}&namespace_stick=true&repository_stick=true&back_to=/namespaces/${namespace}/repository/runners?repository=${repositoryObj?.name}%26repository_id=${repositoryObj?.id}`); }}
onClick={() => { navigate(`/builders/setup/${repositoryObj?.builder?.id}?namespace=${namespace}&namespace_id=${repositoryObj?.namespace_id}&repository=${repositoryObj?.name}&repository_id=${repositoryObj?.id}&namespace_stick=true&repository_stick=true&back_to=/namespaces/${namespace}/repository/runners?repository=${repositoryObj?.name}%26repository_id=${repositoryObj?.id}%26namespace_id=${namespaceId}`); }}
>Update</button>
)
}
Expand Down
44 changes: 8 additions & 36 deletions web/src/pages/Builder/RunnerLog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -213,56 +213,23 @@ export default function ({ localServer }: { localServer: string }) {
<div className="flex flex-col w-0 flex-1 overflow-hidden">
<main className="relative z-0 focus:outline-none">
<Header title="Repository"
// breadcrumb={
// (
// <nav className="flex" aria-label="Breadcrumb">
// <ol className="inline-flex items-center space-x-1 md:space-x-0">
// <li className="inline-flex items-center">
// <Link to={"/namespaces"} className="inline-flex items-center text-sm font-medium text-gray-700 hover:text-blue-600 dark:text-gray-400 dark:hover:text-white">
// <svg className="w-3 h-3 mr-2.5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 20 20">
// <path d="m19.707 9.293-2-2-7-7a1 1 0 0 0-1.414 0l-7 7-2 2a1 1 0 0 0 1.414 1.414L2 10.414V18a2 2 0 0 0 2 2h3a1 1 0 0 0 1-1v-4a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v4a1 1 0 0 0 1 1h3a2 2 0 0 0 2-2v-7.586l.293.293a1 1 0 0 0 1.414-1.414Z" />
// </svg>
// </Link>
// </li>
// <li className="inline-flex items-center">
// <span className="inline-flex items-center text-sm font-medium text-gray-700 hover:text-blue-600 dark:text-gray-400 dark:hover:text-white">
// <Link to={`/namespaces/${namespace}/repositories`} className="inline-flex items-center text-sm font-medium text-gray-700 hover:text-blue-600 dark:text-gray-400 dark:hover:text-white">
// {namespace}
// </Link>
// </span>
// </li>
// <li>
// <div className="flex items-center">
// <span className="text-gray-500 text-sm ml-1">/</span>
// <span className="ml-1 inline-flex items-center text-sm font-medium text-gray-700 hover:text-blue-600 dark:text-gray-400 dark:hover:text-white">
// <Link to={`/namespaces/${namespace}/repository/tags?repository=${repositoryObj?.name}&repository_id=${repositoryObj?.id}`} className="inline-flex items-center text-sm font-medium text-gray-700 hover:text-blue-600 dark:text-gray-400 dark:hover:text-white">
// {repositoryObj?.name?.substring((namespace?.length || 0) + 1)}
// </Link>
// </span>
// <span className="text-gray-500 text-sm ml-1">/</span>
// </div>
// </li>
// </ol>
// </nav>
// )
// }
props={
(
<div className="sm:flex sm:space-x-8">
<Link
to={`/namespaces/${namespace}/repository/summary?repository=${repositoryObj?.name}&repository_id=${repository_id}`}
to={`/namespaces/${namespace}/repository/summary?repository=${repositoryObj?.name}&repository_id=${repository_id}&namespace_id=${namespaceId}`}
className="inline-flex items-center border-b border-transparent px-1 pt-1 text-sm font-medium text-gray-500 hover:border-gray-300 hover:text-gray-700 capitalize"
>
Summary
</Link>
<Link
to={`/namespaces/${namespace}/repository/runners?repository=${repositoryObj?.name}&repository_id=${repository_id}`}
to={`/namespaces/${namespace}/repository/runners?repository=${repositoryObj?.name}&repository_id=${repository_id}&namespace_id=${namespaceId}`}
className="z-10 inline-flex items-center border-b border-indigo-500 px-1 pt-1 text-sm font-medium text-gray-900 capitalize cursor-pointer"
>
Builder
</Link>
<Link
to={`/namespaces/${namespace}/repository/tags?repository=${repositoryObj?.name}&repository_id=${repository_id}`}
to={`/namespaces/${namespace}/repository/tags?repository=${repositoryObj?.name}&repository_id=${repository_id}&namespace_id=${namespaceId}`}
className="inline-flex items-center border-b border-transparent px-1 pt-1 text-sm font-medium text-gray-500 hover:border-gray-300 hover:text-gray-700 capitalize"
>
Tag list
Expand All @@ -285,6 +252,11 @@ export default function ({ localServer }: { localServer: string }) {
)
}
</div>
<div className='pr-2 pl-2 flex gap-1'>
<div className='text-gray-600 px-2 py-2 h-10'>
Elapsed: {runnerObj?.status != "Failed" && runnerObj?.status != "Success" && runnerObj?.status != "Stopped" ? Math.floor((Date.now() - (runnerObj?.started_at || Date.now())) / 1000) : (runnerObj.raw_duration || 0) / 1000}s
</div>
</div>
</div>
</main>
<div className="flex flex-1 overflow-y-auto">
Expand Down
Loading

0 comments on commit 643d413

Please sign in to comment.